如果我想填充4个字节,Little和Big Endian如何看?

Mic*_*tum 3 .net c# endianness

不知何故,我有一个脑筋,无法找出适当的大和小端表示.我有一个字节流,其中存储了32位整数.

整数是1000十进制,即0x03E8十六进制.在Little Endian中,这将被存储为E8 03表示为两个字节.

我假设如果我想要4字节填充,它将被存储为00 00 E8 03.但是,当我使用BitConverter时,我得到了奇怪的结果:

// 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]);
Run Code Online (Sandbox Code Playgroud)

这看起来像BitConverter坏了.文件清楚地说:

GetBytes方法返回的数组中的字节顺序取决于计算机体系结构是little-endian还是big-endian.

那么,我是否误解了Little Endian是如何工作的,BitConverter是破碎的,还是我做错了什么?

Jon*_*eet 5

所以,我误解了Little Endian是如何工作的

对.Little endian意味着最不重要的部分首先出现 - 实际上是1000

Little endian: E8 03 00 00
Big endian:    00 00 03 E8
Run Code Online (Sandbox Code Playgroud)

数量的最低显著字节E8,所以它肯定应该去一个端或其他-小尾数代表所说的那样在开始; big-endian表示将它放在最后.您建议的表示00 00 E8 03将其置于中间.根据Wikipedia Endianness页面,这种表示确实存在,但很少 - 这称为混合端或中端.

代码确认:

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
    }
}
Run Code Online (Sandbox Code Playgroud)