Conversion of byte array hex to decimal

I have a byte array with hexadecimal values, for example:

var b = new byte[] {0x27, 0x01, 0x00, 0x00};

I need to convert this to decimal value, but when I used code below, get unexpected result. Expected is 295, but result is 654376960.

if (BitConverter.IsLittleEndian) Array.Reverse(b);
//int myInt = b[0] | (b[1] << 8) | (b[2] << 16) | (b[3] << 24);
int value = BitConverter.ToInt32(b, 0);

What's wrong?

Jon Skeet
people
quotationmark

Basically your understanding of endianness is wrong - your example is in little-endian format already, so you should only reverse it if BitConverter expects a big-endian format. You just need to invert your condition:

if (!BitConverter.IsLittleEndian) Array.Reverse(b);

(I'd personally put the body of the if statement in braces and new lines, but that's a different matter.)

people

See more on this question at Stackoverflow