我尝试通过下面的C++程序读取二进制数据.但它无法显示值.数据保存为8位无符号字符.让我知道如何解决它.
#include <iostream>
#include <fstream>
using namespace std;
int main(int argc,char *argv[])
{
if(argc!=2)
{
cout << "argument error" << endl;
return 1;
}
ifstream file (argv[1], ios::in|ios::binary);
//ifstream fin( outfile, ios::in | ios::binary );
if (!file)
{
cout << "Can not open file";
return 1;
}
unsigned char d;
while(!file.eof())
{
file.read( ( char * ) &d, sizeof( unsigned char ) );
cout << d << endl;
}
file.close();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
然后针对您的问题:输出一个字符.这意味着流将尝试将其打印为字符,这对于二进制数据来说是不正确的.
如果要打印所读取的值,则需要将其转换为整数.就像是
std::cout << std::hex << std::setw(2) << std::setfill('0') <<
<< static_cast<unsigned int>(d);
Run Code Online (Sandbox Code Playgroud)
以上内容应将值打印为2位十六进制数字.重要的是static_cast.