我有一个文件,包含十六进制文本,我想使用std :: fstream将其作为二进制缓冲区读取
示例文件:
hex.txt
00010203040506070809
读这个应该导致读数从0到9 .
但是下面的代码没有做我想要的 .
using std::ifstream;
int main(int argc, char *argv[])
{
ifstream hexfile("hex.txt");
unsigned char c;
while (hexfile >> std::hex >> std::setw(2) >> c) {
printf ("got %u\n",c); //print as binary, not as char
}
hexfile.close();
return 0;
}
输出:
got 48
got 48
got 48
got 49
got 48
got 50
got 48
got 51
got 48
got 52
got 48
got 53
got 48
got 54
got 48
got 55
got 48
got 56
got 48
got 57
有趣的是,替换unsigned char c; with unsigned int c;没有打印任何结果(即使在第一次读取时,文件流也可能返回false)
我究竟做错了什么? std :: hex应该确保,该输入被解释为十六进制std :: setw(2)应该确保每次迭代都读取2个字符
1 回答
std::setw
不影响单个char
的读取,所以你总是一次读一个 .您逐个读取数字作为字符 .
您将它们打印为无符号整数(
%u
不表示二进制,它表示无符号十进制),它为您提供ASCII值(48 - 57) .要从每个数字中获取相应的整数,请从中减去
'0'
.如果要将文件解释为两个字符的十六进制序列,请先将两个字符读入字符串,然后使用
std::istringstream
和std::hex
来提取数字 .