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

标签 c++ c++11 binary byte

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

[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/

相关文章:

c++ - 在游戏开发中使用杂波

c++ - 指向对齐内存的指针

C++ 位运算 : How to decode/decompress char to int, 并显示正确的字符串?

c - 为什么我的将十进制数转换为二进制数的程序不起作用?

javascript - 在javascript中将十进制打印为二进制

c++ - cuda 共享库链接 : undefined reference to cudaRegisterLinkedBinary

c++ - 使用 std::invoke 调用模板函数

c++ - 简单(moSTLy)变量解析器

c++ - 为什么 const double && 不适用于左值引用?

Java - 二进制标志 vector