gpt4 book ai didi

c++ - 在 C++ 中读取字节

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:30:25 24 4
gpt4 key购买 nike

我试图从二进制文件中读取字节但没有成功。我尝试了很多解决方案,但没有得到结果。文件结构:

[offset] [type]          [value]          [description] 
0000 32 bit integer 0x00000803(2051) magic number
0004 32 bit integer 60000 number of images
0008 32 bit integer 28 number of rows
0012 32 bit integer 28 number of columns
0016 unsigned byte ?? pixel
0017 unsigned byte ?? pixel
........
xxxx unsigned byte ?? pixel

我是如何尝试的(不起作用):

auto myfile = fopen("t10k-images.idx3-ubyte", "r");
char buf[30];
auto x = fread(buf, 1, sizeof(int), myfile);

最佳答案

将字节读取为unsigned char:

ifstream if;

if.open("filename", ios::binary);

if (if.fail())
{
//error
}

vector<unsigned char> bytes;

while (!if.eof())
{
unsigned char byte;

if >> byte;

if (if.fail())
{
//error
break;
}

bytes.push_back(byte);
}

if.close();

然后将多个字节转成一个32位整数例如:

uint32_t number;

number = ((static_cast<uint32_t>(byte3) << 24)
| (static_cast<uint32_t>(byte2) << 16)
| (static_cast<uint32_t>(byte1) << 8)
| (static_cast<uint32_t>(byte0)));

这应该涵盖字节序问题。 int 在系统上显示为 B0B1B2B3 还是 B3B2B1B0 并不重要,因为转换是由位移处理的。该代码不假定内存中的任何特定顺序。

关于c++ - 在 C++ 中读取字节,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12876361/

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