【发布时间】:2014-09-26 13:56:46
【问题描述】:
我必须读取一个二进制文件,所以我使用以下代码:
static void ReadBin()
{
var sectors = new List<Sector>();
using (var b = new BinaryReader(File.Open("C:\\LOG.BIN", FileMode.Open)))
{
const int offset = 4096;
const int required = 2;
int pos = 0;
var length = (int)b.BaseStream.Length;
while (pos < length)
{
for (int i = 1; i <= 640; i++)
{
pos = (offset*i)-2;
b.BaseStream.Seek(pos, SeekOrigin.Begin);
// Read the next 2 bytes.
byte[] by = b.ReadBytes(required);
sectors.Add(new Sector { Number = i, Position = pos, Type = Sector.SetTypeFromExadecimalString(ByteArrayToString(@by)) });
pos = pos + 2;
}
}
}
}
如您所见,ByteArrayToString 获取字节数组并写入一个字符串。 ByteArrayToString 的代码是:
public static string ByteArrayToString(byte[] ba)
{
StringBuilder hex = new StringBuilder(ba.Length * 2);
foreach (byte b in ba)
hex.AppendFormat("{0:x2}", b);
return string.Format("0x{0}", hex.ToString().ToUpper());
}
编写.bin 文件的机器用LittleEndian 写入。因此,按照这个 StackOverflow 线程“Is .NET BinaryReader always little-endian, even on big-endian systems?”,我应该采用“所有”LittleEndian 格式(ReadBytes 以及机器生成的文件)。 问题是函数 ByteArrayToString() 给了我这个结果: 0xF0FF 是 BigEndian 而不是 LittleEndian(事实上我想我应该收到 0xFFF0),因为在那之后我必须解码很多数据,我可以'不确定结果的一致性(我没有什么可比的),我不想解码.bin文件有问题,我怎样才能获得g 0xFFF0?
【问题讨论】:
标签: c# binary endianness