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?
intis always stored as 4 bytes.GetBytes()doesn't always only return byte arrays that are 4 long, it's only doing that because you're using theintdata type. You could use this answer to calculate the minimum number of bytes needed to hold your integer values (presumable returning the 4, 3, 2, and 1 sizes as listed), then trim the result of.GetBytes()to that length before copying to your final byte array.inttypes. If you are sure you really only need 3, 2, or 1 byte for b, c, and d, then c and d can beshortandbyte, giving you exactly what you need. Your result for b depends on endianness, but you can truncate the array, e.g.Array.Copy(BitConverter.GetBytes(data.b), 0, result, 4, 3). I.e. if you don't want all the bytes, then don't copy all the bytes.