active92 active92 - 2 months ago 26
C# Question

Convert int to different size of byte array

I have a byte array

result
. I would like to convert my type called
Info
which are all
int
to the byte array but all of them are in different size.


a = 4 bytes

b = 3 bytes

c = 2 bytes

d = 1 bytes


This is the code I've tried.

private byte[] getInfoByteArray(Info data)
{
byte[] result = new byte[10];
BitConverter.GetBytes((data.a)).CopyTo(result, 0);
BitConverter.GetBytes((data.b)).CopyTo(result, 4);
BitConverter.GetBytes((data.c)).CopyTo(result, 7);
result [9] = Convert.ToByte(data.d);

return result;
}


However, I found out that
BitConverter.GetBytes
returns 4 bytes.

Are there any general solutions that can get different size of bytes to a byte array?

Answer

Use Array.Copy(Array, Int32, Array, Int32, Int32) method:

byte[] result = new byte[10];
Array.Copy(BitConverter.GetBytes(data.a), 0, result, 0, 4);
Array.Copy(BitConverter.GetBytes(data.b), 0, result, 4, 3);
Array.Copy(BitConverter.GetBytes(data.c), 0, result, 7, 2);
Array.Copy(BitConverter.GetBytes(data.d), 0, result, 9, 1);

This assumes little endian hardware. If your hardware is big endian, use

byte[] result = new byte[10];
Array.Copy(BitConverter.GetBytes(data.a), 0, result, 0, 4);
Array.Copy(BitConverter.GetBytes(data.b), 1, result, 4, 3);
Array.Copy(BitConverter.GetBytes(data.c), 2, result, 7, 2);
Array.Copy(BitConverter.GetBytes(data.d), 3, result, 9, 1);
Comments