views:

107

answers:

3

Hi,

Im trying to cast a 4 byte array to an ulong in C#. I'm currently using this code:

atomSize = BitConverter.ToUInt32(buffer, 0);

The byte[4] contians this:

0 0 0 32

However, the bytes are big-endian. Is there a simple way to convert this big-endian ulong to a little-endian ulong?

+6  A: 

I believe that the EndianBitConverter in Jon Skeet's MiscUtil library can do what you want.

You could also swap the bits using bit shift operations:

uint swapEndianness(uint x)
{
    return ((x & 0x000000ff) << 24) +  // First byte
           ((x & 0x0000ff00) << 8) +   // Second byte
           ((x & 0x00ff0000) >> 8) +   // Third byte
           ((x & 0xff000000) >> 24);   // Fourth byte
}

Usage:

atomSize = BitConverter.ToUInt32(buffer, 0);
atomSize = swapEndianness(atomSize);
Mark Byers
Thanks, maybe you could show me what you are doing per line? That would be awesome, I've never used bit shifting until now.
WesleyE
@WesleyE: I've rewritten it to make it a little clearer. It handles one byte at a time, masks out the 8 bits and then shifts then into their new position. The four bytes are then added together to give the result. If you don't understand what bitshifting is, I recommend this question + answer: http://stackoverflow.com/questions/141525/absolute-beginners-guide-to-bit-shifting
Mark Byers
+2  A: 

System.Net.IPAddress.NetworkToHostOrder(atomSize); will flip your bytes.

Mark H
+2  A: 

I recommend using Mono's DataConvert which is like BitConverter on steroids. It allows you to read in big-endian byte arrays directly and improves massively on BitConverter.

A direct link to the source is here.

Callum Rogers