3

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?

mu is too short
  • 426,620
  • 70
  • 833
  • 800
Ruslan F.
  • 5,498
  • 3
  • 23
  • 42

2 Answers2

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