An Integer in C# is stored using 4 bytes with the values ranging from -2,147,483,648 to 2,147,483,647. Use the BitConverter.GetBytes() method to convert an integer to a byte array of size 4.

One thing to keep in mind is the endianness of the output. BitConverter.GetBytes returns the bytes in the same endian format as the system. This is most likely little-endian in your case. If you need the output in big-endian format (which is the standard as per RFC1014 3.2) the output byte array needs to be reversed using Array.Reverse().

Here’s the portable version of the entire code that checks the endianness of the system and always returns the byte array in Big-Endian format.

1
2
3
4
int number;
byte[] bytes = BitConverter.GetBytes(number);
if (BitConverter.IsLittleEndian)
    Array.Reverse(bytes);
Rating: 4.4/5. From 17 votes.
Please wait...
Tagged with: