views:

256

answers:

4

Hello,

I have this function in C# to convert a little endian byte array to an integer number:

int LE2INT(byte[] data)
{
  return (data[3] << 24) | (data[2] << 16) | (data[1] << 8) | data[0];
}

Now I want to convert it back to little endian.. Something like

byte[] INT2LE(int data)
{
  // ...
}

Any idea?

Thanks.

+5  A: 

Just do it in reverse:

result[3]= (data >> 24) & 0xff;
result[2]= (data >> 16) & 0xff;
result[1]= (data >> 8)  & 0xff;
result[0]=  data        & 0xff; 
MSN
+2  A: 

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;
  }
John Knoeller
Why would your example work only on a little-endian machine? AFAIK the bit shift method should be endian-agnostic.
nonoitall
@John, I'm pretty sure you're code works fine whether the code runs on a big- or little-endian architecture. In either case, b[0] is the lowest order byte, b[1] is the next-lowest order byte, and so on.
Dale Hagglund
My mistake, since this code returns LE rather than the natural byte order of the underlying cpu, it will work on all architectures. I'll remove the incorrect text.
John Knoeller
A: 

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);
        }
Eric
A: 

Depending on what you're actually doing, you could rely on letting the framework handle the details of endianness for you by using IPAddress.HostToNetworkOrder and the corresponding reverse function. Then just use the BitConverter class to go to and from byte arrays.

MikeP