假设我们有一个二进制文件,其中包含 2 个字节,反过来形成一个整数。
例如,字节显示如下:(十六进制)
EB 03 00 00
应该这样解释:
00 00 03 EB
哪个 C# 应该能够输入十进制 1003
。如果内存中的 EB
和 03
字节已经存在于 2 个不同的变量中,这是否可行?我可以在这里应用一些数学运算,从数字 235
和 3
形成十进制 1003
吗?或者我应该完全不同吗?
提前致谢!
最佳答案
你说的叫Endianness ,特别是 Little Endian 格式。
在 C# 中,使用 BinaryReader
可能是最简单的或 BinaryWriter
从包含字节顺序正确转换的二进制文件中读取。
以下示例展示了如何使用 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
}
}
}
}
Little endian 是 Intel(和 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);
}
}
LukeH提供了一个链接,进一步讨论与 Endianness 相关的问题,例如针对 Xbox 360(恰好是 Big Endian 平台)时:
One Little, Two Little, Three Little Endian... 0x0A Big Endian Bugs
更新
MiscUtil 库提供了一个二进制读取器/写入器类,可以针对特定的字节顺序进行配置:
MiscUtil.IO.EndianBinary{Writer/Reader}
关于c# - 你如何称呼这种二进制数据类型,以及如何在 C# 中处理它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3782889/