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

查看:876
本文介绍了为什么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重新presents uints?它是在不同的平台上使用相同(我正在运行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)?

推荐答案

这似乎是一个字节序的问题。 说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位,第2 LSB了8位,第3 LSB下8位,第4 LSB(最高位)下降了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天全站免登陆