Search code examples
c#arraysbitconverter

C# BitConverter problems


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.