Convert Integers to Byte Arrays
by Mattias Sjögren and Juval Löwy
March 2003 Issue
Technology Toolbox: C#
Q: Convert Integers to Byte Arrays
How can I convert an int to a byte array, and vice versa, in C#?
A:
You can accomplish this in at least three ways (see Listing 1). A class called BitConverter in the System namespace of the .NET Framework class library is dedicated to this task. It has a GetBytes method, with overloads for most simple types, which returns a byte array with the in-memory representation of the value you pass in. It also has a number of ToTypeName methods for doing the opposite—converting a byte array to a primitive type:
byte[] b = BitConverter.GetBytes(
0xba5eba11 );
//{0x11,0xba,0x5e,0xba}
uint u = BitConverter.ToUInt32(
new byte[] {0xfe, 0x5a, 0x11,
0xfa},0 ); // 0xfa115afe
An important thing to keep in mind when you use the BitConverter class is that its behavior depends on the endianness of the hardware architecture the code runs on—that is, the order in which the bytes of an integer are stored in memory. Problems can arise if you persist the bits to a file format that should be readable on many different platforms. The BitConverter has a public IsLittleEndian field that you can check to determine how it will behave, but unfortunately it doesn't provide a way for you to change it.
It's also possible to do without the BitConverter class and do the work manually with some bit shifting instead:
b = new byte[] {0xfe,0x5a,0x11,0xfa};
u = (uint)(b[0] | b[1] << 8 |
b[2] << 16 | b[3] << 24);
b[0] = (byte)(u);
b[1] = (byte)(u >> 8);
b[2] = (byte)(u >> 16);
b[3] = (byte)(u >> 24);
This way you can get around the endian problem, because you have full control over which byte ends up where.
Finally—if you don't mind using unsafe code—you can do a direct memory copy by casting a pointer to the byte array to a pointer to the integer type, then dereferencing it:
unsafe {
fixed ( byte* pb = b )
u = *((uint*)pb);
}
The exact result of this operation depends on the hardware the code runs on, as it does with the BitConverter.
If you're going to do a lot of this kind of conversion—in a tight loop, say—and want the best performance, I suggest you use one of the last two methods. The BitConverter tends to be somewhat slower, although the difference isn't big. —M.S.
Back to top
|