我正在尝试将从文件中读取的十六进制代码存储到缓冲区中,然后将其显示在控制台上,到目前为止,它似乎不起作用。这是我的代码:
using namespace std;
int main()
{
ifstream file("Fishie.ch8",ios::binary);
if (!file.is_open())
{
cout << "Error";
}
else
{
file.seekg(0, ios::end);
streamoff size = file.tellg();
file.seekg(0, ios::beg);
char *buffer = new char[size];
file.read(buffer, size);
file.close();
for (int i = 0; i < size; i++)
{
cout <<hex<< buffer[i] << " ";
}
}
delete[] buffer;
cin.get();
}
预期输出应为:
00 e0 a2 20 62 08 60 f8 70 08 61 10 40 20 12 0e
d1 08 f2 1e 71 08 41 30 12 08 12 10 00 00 00 00
00 00 00 00 00 18 3c 3c 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
3e 3f 3f 3b 39 38 38 38 00 00 80 c1 e7 ff 7e 3c
00 1f ff f9 c0 80 03 03 00 80 e0 f0 78 38 1c 1c
38 38 39 3b 3f 3f 3e 3c 78 fc fe cf 87 03 01 00
00 00 00 00 80 e3 ff 7f 1c 38 38 70 f0 e0 c0 00
3c 18 00 00 00 00 00 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
答案 0 :(得分:3)
当缓冲区为char
时,所有元素都将打印为字符。您想要的是将数字转换为十六进制。
顺便说一句:当您想转换为十六进制输出时,是否真的要从文件或char
中读取unsigned char
是一个问题。
您发现,istream.read
的签名使用char
,因此您必须先转换为unsigned char
,然后再转换为unsigned int
,例如:
cout <<hex<< (unsigned int)(unsigned char) buffer[i] << " ";
对于真正的c ++用户,您应该写一个很好的static_cast
;)
这将打印出十六进制值。但是,如果您有CR
,则会看到一个'a'而不是'0a',因此您必须先设置宽度并填充char:
cout.width(2);
cout.fill('0');
for (int i = 0; i < size; i++)
{
cout <<hex<< (unsigned int)(unsigned char)buffer[i] << " ";
}
顺便说一句:delete[] buffer;
的作用域错误,必须在定义它的作用域内转移。