C# BitConverter problems
-
27-10-2019 - |
Question
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?
Solution
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.
OTHER TIPS
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);
}