Normaly if you want for example represent 5 in byte array it will be smth like {0x00,0x00,0x00,0x05} but BitConverter gives me reversed array({0x05,0x00,0x00,0x00}) Why it is so and where I'm wrong?
Asked
Active
Viewed 1,724 times
3
-
1http://msdn.microsoft.com/en-us/library/system.bitconverter.aspx Big vs little endian? – Per Fagrell Dec 03 '11 at 08:02
2 Answers
3
Odds are that you are on a little-endian architecture (which is the case for the common x86 and x86-64 architectures). You can verify this with the BitConverter.IsLittleEndian
property.
On such an architecture, the least significant byte comes first, which explains why
BitConverter.GetBytes(5)
produces
{ 0x05, 0x00, 0x00, 0x00 }
You could of course reverse the array if required based on the system/target endianness. You can find such an EndianBitConverter
listed here.

Ani
- 111,048
- 26
- 262
- 307
0
I wrote the following wrapper classes to handle the case of the BitConverter
expecting Little Endien.
public static Int16 ToInt16(byte[] data, int offset)
{
if (BitConverter.IsLittleEndian)
{
return BitConverter.ToInt16(BitConverter.IsLittleEndian ? data.Skip(offset).Take(2).Reverse().ToArray() : data, 0);
}
return BitConverter.ToInt16(data, offset);
}
public static Int32 ToInt32(byte[] data, int offset)
{
if (BitConverter.IsLittleEndian)
{
return BitConverter.ToInt32(BitConverter.IsLittleEndian ? data.Skip(offset).Take(4).Reverse().ToArray() : data, 0);
}
return BitConverter.ToInt32(data, offset);
}
public static Int64 ToInt64(byte[] data, int offset)
{
if (BitConverter.IsLittleEndian)
{
return BitConverter.ToInt64(BitConverter.IsLittleEndian ? data.Skip(offset).Take(8).Reverse().ToArray() : data, 0);
}
return BitConverter.ToInt64(data, offset);
}

Zapnologica
- 22,170
- 44
- 158
- 253