C# Convert Int to Byte Array
By FoxLearn 1/20/2025 9:07:13 AM 13
How to Convert an Integer to a Byte Array in C#?
An integer (int
) in C# is represented using 4 bytes (32 bits). It can store values ranging from -2,147,483,648 to 2,147,483,647.
These 4 bytes represent the integer in memory, and converting this representation into a byte array can be useful for various purposes, such as serialization or network communication.
For example, Using BitConverter.GetBytes()
C# provides the BitConverter.GetBytes()
method to convert an integer into a byte array of size 4.
int number = 12345; byte[] bytes = BitConverter.GetBytes(number);
One critical aspect to consider is the endianness of the output. Endianness determines the order in which bytes are arranged:
Little-endian: The least significant byte comes first.
Big-endian: The most significant byte comes first.
BitConverter.GetBytes()
returns the byte array in the system's native endianness, which is typically little-endian on most modern systems. However, certain protocols and file formats (e.g., RFC1014 3.2) use big-endian as the standard.
If you need the byte array in big-endian format, you can reverse the output using Array.Reverse()
.
The following code ensures the byte array is always returned in big-endian format, regardless of the system's endianness:
int number = 12345; byte[] bytes = BitConverter.GetBytes(number); if (BitConverter.IsLittleEndian) { Array.Reverse(bytes); }
In this example:
BitConverter.GetBytes(number)
generates the byte array in the system's native endianness.BitConverter.IsLittleEndian
checks if the system uses little-endian format.If the system is little-endian,
Array.Reverse(bytes)
reverses the byte array to convert it to big-endian.
- How to fix 'Failure sending mail' in C#
- How to Parse a Comma-Separated String from App.config in C#
- How to convert a dictionary to a list in C#
- How to retrieve the Executable Path in C#
- How to validate an IP address in C#
- How to retrieve the Downloads Directory Path in C#
- C# Tutorial
- Dictionary with multiple values per key in C#