C# Convert Int to Byte Array
By FoxLearn 1/20/2025 9:07:13 AM 191
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.
- Using the OrderBy and OrderByDescending in LINQ
- Querying with LINQ
- Optimizing Performance with Compiled Queries in LINQ
- MinBy() and MaxBy() Extension Methods in .NET
- SortBy, FilterBy, and CombineBy in NET 9
- Exploring Hybrid Caching in .NET 9.0
- Using Entity Framework with IDbContext in .NET 9.0
- Primitive types in C#