【发布时间】:2010-01-05 00:32:36
【问题描述】:
在下面的代码中,为什么 X 和 Y 的值与我直观地认为的不同?
如果字节 0-7 被写入缓冲区,那么生成的 long 不应该具有相同顺序的字节吗?这就像它以相反的顺序读取长值。
x 0x0706050403020100 long
y 0x0706050403020100 long
z 0x0001020304050607 long
MemoryStream ms = new MemoryStream();
byte[] buffer = new byte[] { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07 };
ms.Write(buffer, 0, buffer.Length);
ms.Flush();
ms.Position = 0;
BinaryReader reader = new BinaryReader(ms);
long x = reader.ReadInt64();
long y = BitConverter.ToInt64(buffer, 0);
long z = BitConverter.ToInt64(buffer.Reverse<byte>().ToArray<byte>(), 0);
byte[] xbytes = BitConverter.GetBytes(x);
byte[] ybytes = BitConverter.GetBytes(y);
byte[] zbytes = BitConverter.GetBytes(z);
(除了 .NET 之外,我不知道如何标记这个问题。)
BitConverter.IsLittleEndian
是假的。如果我的电脑是大端的,为什么会这样?
- 这是一台 Windows 7 64 位机器
- Intel Core2 Quad Q9400 2.66 GHz LGA 775 95W 四核处理器型号 BX80580Q9400
- SUPERMICRO MBD-C2SBX+-O LGA 775 Intel X48 ATX Intel 主板
这段代码的结果(回应Jason的评论):
byte[] buffer = new byte[] { 0x00, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07 };
long y = BitConverter.ToInt64(buffer, 1);
Console.WriteLine(BitConverter.IsLittleEndian);
Console.WriteLine(y);
结果:
False
506097522914230528
【问题讨论】:
-
添加标签供您搜索:)
-
你能提供机器的规格(处理器、mb、O/S)吗?
-
这是 Intel Core 2,Windows 7。我还应该补充一点,BitConverter.IsLittleEndian 返回 false。
-
请您执行以下操作:
byte[] buffer = new byte[] { 0x00, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07 }; long y = BitConverter.ToInt64(buffer, 1);并报告y的值。请注意,buffer比您给出的定义多了一个字节。我无法访问BitConverter.IsLittleEndian为假的机器。 -
Jason:我在票的编辑 2 中回答了你的问题。
标签: .net endianness