【问题标题】:filestream reading hexadecimal file into binary buffer文件流将十六进制文件读入二进制缓冲区
【发布时间】:2014-11-21 11:11:01
【问题描述】:

我有一个包含十六进制文本的文件,我想使用 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;带无符号整数 c; 不会打印任何内容(即使在第一次读取时文件流也可能返回 false)

我做错了什么? std::hex 应该确保输入被解释为十六进制 std::setw(2) 应该确保每次迭代都读取 2 个字符

【问题讨论】:

    标签: c++ iostream


    【解决方案1】:

    std::setw 不影响阅读单个chars,因此您始终一次阅读一个。

    您将数字一个一个地读取为字符。
    您将它们打印为无符号整数(%u 不表示二进制,它表示无符号十进制),这会为您提供 ASCII 值(48 - 57)。

    要从每个数字中获取相应的整数,请从中减去'0'

    printf ("got %u\n", c - '0');
    

    如果要将文件解释为两个字符的十六进制序列,首先将两个字符读入一个字符串,然后使用std::istringstreamstd::hex 提取数字。

    int main(int argc, char *argv[])
    {
       std::ifstream hexfile("hex.txt");
       std::string x;
       while (hexfile >> std::setw(2) >> x) {
          std::istringstream y(x);
          unsigned int i;
          y >> std::hex >> i;
          printf ("got %u\n", i);
       }    
    }
    

    【讨论】:

      猜你喜欢
      • 2020-10-25
      • 2012-10-03
      • 1970-01-01
      • 2015-05-09
      • 2011-12-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-27
      相关资源
      最近更新 更多