[英]ifstream::read keeps returning incorrect values
我正在嘗試讀取.bin文件並返回十六進制值。 一切正常,直到必須讀取“ F0”或“ A0”之類的值為止。 它不斷返回“ fffff0”或“ ffffa0”。 當我修改函數以返回十進制值時,控制台將顯示“ -16”和“ -96”,而所有其他正確的返回值均為正。
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的最高位置1時,它表示一個負值(例如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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.