为什么 BinaryReader.ReadUInt32() 反转位模式? [英] Why does BinaryReader.ReadUInt32() reverse the bit pattern?

查看:29
本文介绍了为什么 BinaryReader.ReadUInt32() 反转位模式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 BinaryReader 类读取二进制文件,我需要将它作为 UInt32 块读取,然后进行一些位移等后记.

I am trying to read a binary file with the BinaryReader class, and I need to read it in as blocks of UInt32, and then do some bit shifting etc. afterwords.

但是,由于某种原因,当我使用 ReadUInt32 方法时,位顺序颠倒了.

But, for some reason bit order is reversed when I use the ReadUInt32 method.

例如,如果我有一个文件,其中前四个字节在十六进制中看起来像这样,0x12345678,它们在被 ReadUInt32 读取后最终是这样的:0x78563412.

If I for example have a file where the first four bytes looks like this in hex, 0x12345678, they end up like this after being read by ReadUInt32: 0x78563412.

如果我使用 ReadBytes(4) 方法,我会得到预期的数组:

If I use the ReadBytes(4) method, I get the expected array:

[0x00000000]    0x12    byte
[0x00000001]    0x34    byte
[0x00000002]    0x56    byte
[0x00000003]    0x78    byte

这是为什么?它只是 .net 在内存中表示 uint 的方式吗?它在不同平台上是否相同(我运行的是 64 位 Windows 7、.net 3.5 sp1)?

Why is this? Is it just the way .net represents uints in memory? Is it the same across the different platforms (I am running 64bit Windows 7, .net 3.5 sp1)?

推荐答案

这似乎是一个 endianness 问题.文档说 ReadUint32 以小端读取所以第一个字节是最不重要的,所以它进入最低的内存位置.你的作者一定是大端的吗?

This seems to be an endianness issue. The docs say ReadUint32 reads in little-endian so the first byte is the least-significant so it goes to the lowest memory location. Your writer must be big-endian?

BinaryWriter.Write(UInt32) 说它写 也是小端.你的二进制数据源不是 BinaryWriter 吗?

BinaryWriter.Write(UInt32) says it writes little-endian too. Is your binary data source not BinaryWriter?

基本上你需要做的是修复它:

Essentially what you need to do to fix it is this:

uint a = 0x12345678;
uint b = ((a & 0x000000FF) << 24) + ((a & 0x0000FF00) << 8) + ((a & 0x00FF0000) >> 8) + ((a & 0xFF000000) >> 24);

这会将最低有效字节向上移动 24 位,将第二个 LSB 向上移动 8 位,将第三个 LSB 向下移动 8 位,将第四个 LSB(MSB)向下移动 24 位.这在几个库中都有介绍.

This shifts the least-significant byte up 24 bits, the 2nd LSB up 8 bits, the 3rd LSB down 8 bits, and the 4th LSB (the MSB) down 24 bits. Doing this is covered in several libraries.

也许使用 BitConverter 会更清楚一点:

Perhaps using BitConverter would be a bit more clear:

uint a = 0x12345678;
byte[] bytes = BitConverter.GetBytes(a);
// Swap byte order
uint b = BitConverter.ToUInt32(new byte[] { bytes[3], bytes[2], bytes[1], bytes[0] }, 0);

这篇关于为什么 BinaryReader.ReadUInt32() 反转位模式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆