How to convert an int to a little endian byte array?
Could you use the BitConverter class? It will only work on little-endian hardware I believe, but it should handle most of the heavy lifting for you.
The following is a contrived example that illustrates the use of the class:
if (BitConverter.IsLittleEndian)
{
int someInteger = 100;
byte[] bytes = BitConverter.GetBytes(someInteger);
int convertedFromBytes = BitConverter.ToInt32(bytes, 0);
}
Just reverse it, Note that this this code (like the other) works only on a little Endian machine. (edit - that was wrong, since this code returns LE by definition)
byte[] INT2LE(int data)
{
byte[] b = new byte[4];
b[0] = (byte)data;
b[1] = (byte)(((uint)data >> 8) & 0xFF);
b[2] = (byte)(((uint)data >> 16) & 0xFF);
b[3] = (byte)(((uint)data >> 24) & 0xFF);
return b;
}
The BitConverter
class can be used for this, and of course, it can also be used on both little and big endian systems.
Of course, you'll have to keep track of the endianness of your data. For communications for instance, this would be defined in your protocol.
You can then use the BitConverter
class to convert a data type into a byte array and vice versa, and then use the IsLittleEndian
flag to see if you need to convert it on your system or not.
The IsLittleEndian
flag will tell you the endianness of the system, so you can use it as follows:
This is from the MSDN page on the BitConverter
class.
int value = 12345678; //your value
//Your value in bytes... in your system's endianness (let's say: little endian)
byte[] bytes = BitConverter.GetBytes(value);
//Then, if we need big endian for our protocol for instance,
//Just check if you need to convert it or not:
if (BitConverter.IsLittleEndian)
Array.Reverse(bytes); //reverse it so we get big endian.
You can find the full article here.
Hope this helps anyone coming here :)
Just do it in reverse:
result[3]= (data >> 24) & 0xff;
result[2]= (data >> 16) & 0xff;
result[1]= (data >> 8) & 0xff;
result[0]= data & 0xff;