Michael Stum
Michael Stum

Reputation: 181044

How do Little and Big Endian look if I want padding to 4 bytes?

Somehow I'm having a brainfart and can't figure out proper big and little endian representations. I have a bytestream in which a 32-Bit Integer is stored.

The Integer is 1000 decimal, which is 0x03E8 hexadecimal. In little Endian, this would be stored as E8 03 when represented as two bytes.

I assumed that if I want 4 byte padding, it would be stored as 00 00 E8 03. However, when I use the BitConverter, I get strange results:

// true
Console.WriteLine(BitConverter.IsLittleEndian);

var bytes = new byte[4] { 0x00, 0x00, 0xE8, 0x03 };
var convertedInt = BitConverter.ToInt32(bytes,0);
// 65536000 ?!
Console.WriteLine(convertedInt);

var inputInt = 1000;
var convertedBytes = BitConverter.GetBytes(inputInt);
// 4 Bytes: e8 03 00 00
Console.WriteLine("{0} Bytes: {1:x2} {2:x2} {3:x2} {4:x2}", convertedBytes.Length,
        convertedBytes[0],  convertedBytes[1],
        convertedBytes[2],  convertedBytes[3]);

This looks like BitConverter is broken. The documentation clearly says:

The order of bytes in the array returned by the GetBytes method depends on whether the computer architecture is little-endian or big-endian.

So, am I misunderstanding how Little Endian works, is BitConverter broken, or do I do something wrong?

Upvotes: 4

Views: 2582

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1503090

So, am I misunderstanding how Little Endian works

Yup. Little endian means the least significant parts come first - so 1000 would actually be

Little endian: E8 03 00 00
Big endian:    00 00 03 E8

The least significant byte of the number is E8, so surely it should go at one end or the other - little-endian representation puts it at the start; big-endian representation puts it at the end. Your suggested representation of 00 00 E8 03 puts it in the middle. According to the Wikipedia Endianness page, that sort of representation does exist, but only rarely - this is called mixed-endian or middle-endian.

Code to confirm:

using System;

class Test
{
    static void Main()
    {
        var bytes = new byte[4] { 0xE8, 0x03, 0x00, 0x00 };
        var convertedInt = BitConverter.ToInt32(bytes, 0);
        Console.WriteLine(convertedInt); // 1000
    }
}

Upvotes: 8

Related Questions