你如何称呼这种二进制数据类型,以及如何在C#中处理它?

Cod*_*cat 4 c# binary byte file

假设我们有一个二进制文件,其中包含2个字节,形成一个整数,相反.

所以例如,字节显示如下:(十六进制)

EB 03 00 00
Run Code Online (Sandbox Code Playgroud)

哪个应解释为:

00 00 03 EB
Run Code Online (Sandbox Code Playgroud)

哪个C#应该能够以十进制形式输入1003.如果你有2个不同变量的内存EB03字节已经存在,这是否可能?有没有一些数学我可以在这里申请1003从数字形成十进制2353?或者我应该完全不同吗?

提前致谢!

Dir*_*mar 10

你所谈论的是Endianness,特别是Little Endian格式.

在C#中,最简单的方法是使用BinaryReaderBinaryWriter读取包含正确的字节顺序转换的二进制文件.

以下示例显示如何使用a BinaryReader以Little Endian格式获取数字的正确整数解释:

using System.IO;

class EndiannessSample
{
    static void Main(string[] args)
    {
        using (MemoryStream ms = new MemoryStream())
        {
            // write bytes in little-endian format
            ms.WriteByte(0xEB);
            ms.WriteByte(0x03);
            ms.WriteByte(0x00);
            ms.WriteByte(0x00);
            ms.Position = 0;

            using (BinaryReader reader = new BinaryReader(ms))
            {
                int i = reader.ReadInt32(); // decimal value of i is 1003
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Little endian是英特尔(和Windows)平台的标准.如果您必须处理Big Endian格式的数据(例如,在导入在旧Macintosh上创建的文件时),.NET中没有直接支持.您可以编写一个简单的实用程序函数来使用BitConverter类转换字节顺序.在上面的示例中,您可以执行以下操作来处理Big Endian(在Little Endian平台上):

using (MemoryStream ms = new MemoryStream())
{
    // write bytes in big-endian format
    ms.WriteByte(0x00);
    ms.WriteByte(0x00);
    ms.WriteByte(0x03);
    ms.WriteByte(0xEB);

    ms.Position = 0;
    using (BinaryReader reader = new BinaryReader(ms))
    {
        byte[] temp = reader.ReadBytes(4);
        if (BitConverter.IsLittleEndian)
        {
            // reverse the byte order only if we are on a little-endian system,
            // because the BitConverter is aware of the endianness of the system
            //
            Array.Reverse(temp);
        }
        int i = BitConverter.ToInt32(temp, 0);
    }
}
Run Code Online (Sandbox Code Playgroud)

LukeH提供了一个链接,进一步讨论了与Endianness相关的问题,例如在定位Xbox 360(恰好是Big Endian平台)时:

一个小,两个小,三个小端... 0x0A大端错误

更新

所述MiscUtil库提供了可以被配置为特定的字节序的二进制读/写器类:

MiscUtil.IO.EndianBinary{Writer/Reader}
Run Code Online (Sandbox Code Playgroud)

  • @Robert:这不仅仅是一个理论上的可能性:XBox 360是big-endian并运行一个版本的框架; 它也是可能的 - 我不确定 - 紧凑的框架可能会在一些大端平台上运行; 然后,当然,也有单声道.如果你需要固定的字节顺序,无论你的代码在哪里运行,那么你*不能*使用`BitConverter`,因为它总是使用当前的系统字节顺序.http://blogs.msdn.com/b/robunoki/archive/2006/04/05/568737.aspx (2认同)