How to convert a primitive [] to byte []

To serialize a primitive array, I wonder how to convert a primitive [] to its corresponding byte []. (i.e. int [128] to byte [512], or to abbreviation [] to byte [] ...) The destination may be a memory stream, a network message, a file, whatever. The goal is performance (time of serialization and deserialization) in order to be able to write with some byte streams [] in one shot instead of a β€œthrough” cycle for all values ​​or to highlight using some converter.

Some solutions already considered:

Normal write / read loop

//array = any int[];
myStreamWriter.WriteInt32(array.Length);
for(int i = 0; i < array.Length; ++i)
   myStreamWriter.WriteInt32(array[i]);

This solution works for serialization and deserialization. This seems to be 100 times faster than a standard system. Session Duration Serialization in conjunction with BinaryFormater to serialize / deserialize one or more ints.

But this solution becomes slower if array.Length contains more than 200/300 values ​​(for Int32).

Cast

It seems that C # cannot directly pass Int [] to byte [] or bool [] to byte [].

BitConverter.Getbytes ()

This solution works, but it allocates a new byte [] each time the loop is called through my int []. The performances are, of course, terrible.

Marshal.copy

Yup, this solution works too, but the same problem as the previous bit converter.

C ++ hack

Since live broadcasts are not allowed in C #, I tried to hack C ++ after looking in memory that the length of the array is stored 4 bytes before the start of the array data

ARRAYCAST_API void Cast(int* input, unsigned char** output)
{
   // get the address of the input (this is a pointer to the data)
   int* count = input;
   // the size of the buffer is located just before the data (4 bytes before as this is an int)
   count--;
   // multiply the number of elements by 4 as an int is 4 bytes
   *count = *count * 4;
   // set the address of the byte array
   *output = (unsigned char*)(input);
}

#, :

byte[] arrayB = null;
int[] arrayI = new int[128];
for (int i = 0; i < 128; ++i)
   arrayI[i] = i;

// delegate call
fptr(arrayI, out arrayB);

int [128] ++, 'output' var, # [1] . , .

, , , , # (int [] β†’ byte [], bool [] β†’ byte [], double [] β†’ byte []...) /...

?

+4
1

Buffer.BlockCopy?

// serialize
var intArray = new[] { 1, 2, 3, 4, 5, 6, 7, 8 };
var byteArray = new byte[intArray.Length * 4];
Buffer.BlockCopy(intArray, 0, byteArray, 0, byteArray.Length);

// deserialize and test
var intArray2 = new int[byteArray.Length / 4];
Buffer.BlockCopy(byteArray, 0, intArray2, 0, byteArray.Length);
Console.WriteLine(intArray.SequenceEqual(intArray2));    // true

, BlockCopy - / . , , BlockCopy, , , .

+4

All Articles