C# Convert Int to Byte Array

Partho Sarathi

04 Apr, 2018 · 1 minute read

  • Share:

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 endiannessof 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.

int number;
byte[] bytes = BitConverter.GetBytes(number);
if (BitConverter.IsLittleEndian)
    Array.Reverse(bytes);
  • Share:

The cleanest blogging platform


2024 © Maxotek. All rights reserved.