ifstream::read 不断返回不正确的值

ifstream::read keeps returning incorrect values

我正在尝试读取 .bin 文件和 return 十六进制值。一切正常,直到它必须读取 "F0" 或 "A0" 之类的值。它保持 returning "fffff0" 或 "ffffa0"。当我将函数修改为 return 十进制值时,控制台显示“-16”和“-96”,而所有其他正确的 returned 值为正数。

void reader(string input) { 
int size;
char *storage;

ifstream file(input, ios::in | ios::binary);
if (file.is_open()) {
    file.seekg(0, ios::end);
    size = file.tellg();
    storage = new char[size];
    file.seekg(0, ios::beg);
    file.read(storage, size);
    file.close();
    for (int i = 0; i < size; i++) 
    {
        cout << hex << (int)storage[i] << endl;
    }
}
else {cout << "could not open file" << endl;}
}

"char" 是一个带符号的值。当 char 的最高位被设置时,它代表一个负值(例如 0x80 到 0xFF)。当您将负值转换为不同大小的整数时,该值将被保留,从而导致十六进制值不同。

#include <iostream>

int main()
{
    char ch = 0xF0;
    int value = ch;
    std::cout << value << std::endl;
    std::cout << std::hex << value << std::endl;
}

以上程序打印“-16, fffffff0”。该程序实际上相当于:

#include <iostream>

int main()
{
    char ch = -16;
    int value = ch;
    std::cout << value << std::endl;
    std::cout << std::hex << value << std::endl;
}

要获得预期的行为,您需要屏蔽值:

#include <iostream>

int main()
{
    char ch = 0xF0;
    int value = ch & 0xFF;
    std::cout << value << std::endl;
    std::cout << std::hex << value << std::endl;
}