gpt4 book ai didi

c# - 在 C# 中使用 BinaryReader 解析 MNIST 数据集时我做错了什么?

转载 作者:行者123 更新时间:2023-11-30 14:11:11 26 4
gpt4 key购买 nike

我正在用 C# 解析 MNIST 数据集,来自:http://yann.lecun.com/exdb/mnist/

我正在尝试从二进制文件中读取第一个 Int32:

FileStream fileS = new FileStream(fileName, FileMode.Open, FileAccess.Read);
BinaryReader reader = new BinaryReader(fileS);
int magicNumber = reader.ReadInt32();

但是,它给了我一个无意义的数字:50855936。

如果我使用 File.ReadAllBytes()

buffer = File.ReadAllBytes(fileName);

然后查看字节,它工作正常(前四个字节现在代表 2049),我对 BinaryReader 做错了什么?

文件格式如下(我正在尝试读取第一个魔数(Magic Number)):

All the integers in the files are stored in the MSB first (high endian) format used by most non-Intel processors. Users of Intel processors and other low-endian machines must flip the bytes of the header.

训练集标签文件(train-labels-idx1-ubyte):

[offset] [type]          [value]          [description] 
0000 32 bit integer 0x00000801(2049) magic number (MSB first)
0004 32 bit integer 60000 number of items
0008 unsignebyte ?? label
0009 unsigned byte ?? label
........
xxxx unsigned byte ?? label
The labels values are 0 to 9.d

最佳答案

50855936 == 0x03080000。或者 0x00000803 当你反转字节时,几乎所有机器都需要,因为小端已经赢得了鸡蛋 war 。足够接近 2049,不知道如何解释 2 的偏移量。这里有一个扩展方法可以帮助您阅读它:

  public static class BigEndianUtils {
public static int ReadBigInt32(this BinaryReader br) {
var bytes = br.ReadBytes(sizeof(Int32));
if (BitConverter.IsLittleEndian) Array.Reverse(bytes);
return BitConverter.ToInt32(bytes, 0);
}
}

如果文件包含更多字段类型,请添加其他方法,只需在代码段中替换 Int32。

关于c# - 在 C# 中使用 BinaryReader 解析 MNIST 数据集时我做错了什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20967088/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com