在 C++ 中使用移位器和缓冲区读取二进制文件

Reading Binary Files Using Bitwise Shifters and Buffers in C++

我正在尝试读取二进制文件并将数据简单地转换为可用的无符号整数。下面的代码适用于某些文件位置的 2 字节读取,并正确打印无符号整数。当我使用 4 字节代码时,虽然我的值结果是一个比预期大得多的数字。我认为问题出在读取函数中,好像我得到了错误的 character/decimal 数字(例如 101),当移位时变成一个比应该的数字大得多的数字(~6662342)。(当程序运行它时不时地抛出一个异常 "stack around the variable buf runtime error #2" in visual studios)。有任何想法吗?这可能是我对数据如何存储在影响我的数据输出的 char 数组中的基本知识。

有效的 2 字节代码

unsigned char buf[2];
    file.seekg(3513);
    uint64_t value = readBufferLittleEndian(buf, &file);

    printf("%i", value);

    system("PAUSE");
    return 0;

}


uint64_t readBufferLittleEndian(unsigned char buf[], std::ifstream *file)
{
    file->read((char*)(&buf[0]), 2);
    return (buf[1] << 8 | buf[0]);
}

损坏的 4 字节代码

unsigned char buf[8 + 1]; //= { 0, 2 , 0 , 0 , 0 , 0 , 0, 0, 0 };
    uint64_t buf1[9];
    file.seekg(3213);
    uint64_t value = readBufferLittleEndian(buf, &file, buf1);

    std::cout << value;


    system("PAUSE");
    return 0;

}


uint64_t readBufferLittleEndian(unsigned char buf[], std::ifstream *file, uint64_t buf1[])
{
    file->read((char*)(&buf[0]), 4);
    for (int index = 0; index < 4; index++)
    {
        buf1[index] = buf[index];
    }
    buf1[0];
    buf1[1];
    buf1[2];
    buf1[3];
    //return (buf1[7] << 56 | buf1[6] << 48 | buf1[5] << 40 | buf1[4] << 32 | buf1[3] << 24 | buf1[2] << 16 | buf1[1] << 8 | buf1[0]);
    return (buf1[3] << 24 | buf1[2] << 16 | buf1[1] << 8 | buf1[0]);
    //return (buf1[1] << 8 | buf1[0]);
}
Please correct me if I got the endianess reversed.

代码是 C++ 除了 printf 行

你必须在转移前施法。您不能将 char 左移 56 位。

((uint64_t)buf[n] << NN

Seekg(0) = 字节 1,seekg(3212) = 字节 3213。不完全确定为什么我之前在字节 3214 中得到一个零,考虑到我现在得到 220(表示大端)。获得 220 表明我正在解释 seekg() 的功能。哦,好吧,不管怎样,现在重要的地方已经解决了。