【问题标题】:C++ Text File ReadingC++ 文本文件读取
【发布时间】:2011-01-26 18:04:05
【问题描述】:

所以我需要一点帮助,我目前有一个包含以下数据的文本文件:

myfile.txt
-----------
b801000000

我想要做的是将 b801 等数据读取为位,这样我就可以获得

的值
0xb8 0x01 0x00 0x00 0x00.

当前我正在使用以下 typedef 将该行读入无符号字符串。

typedef std::basic_string <unsigned char> ustring;
ustring blah = reinterpret_cast<const unsigned char*>(buffer[1].c_str());

我一直在努力让每个字符 {'b', '8' etc...} 真正成为 { '0xb8', '0x01' etc...}

感谢任何帮助。

谢谢。

【问题讨论】:

标签: c++ file-io formatting


【解决方案1】:

我看到了两种方式:

  1. 以std::ios::binary 的身份打开文件并使用std::ifstream::operator&gt;&gt; 在使用标志std::ios_base::hex 并提取为两个字节大的类型(如stdint.h's (C+ +0x/C99) uint16_t 或等效)。有关使用std::stringstreams 的示例,请参阅@neuro 对您的问题的评论。 std::ifstream 的工作原理几乎相同。

  2. 直接访问流迭代器并手动执行转换。更难,更容易出错,也不一定更快,但仍然很有可能。

【讨论】:

    【解决方案2】:

    strtol 将字符串(需要以 null 结尾的 C 字符串)转换为具有指定基数的 int

    【讨论】:

      【解决方案3】:

      这是一种肮脏的做法:

      #include <stdio.h>
      
      int main ()
      {
        int num;
        char* value = "b801000000";
      
        while (*value) {
          sscanf (value, "%2x", &num);
          printf ("New number: %d\n", num);
          value += 2;
        }
      
        return 0;
      }
      

      运行这个,我得到:

      New number: 184
      New number: 1
      New number: 0
      New number: 0
      New number: 0
      

      【讨论】:

        猜你喜欢
        • 2021-03-10
        • 2015-05-16
        • 1970-01-01
        • 2014-09-03
        • 2017-05-02
        • 1970-01-01
        • 2011-06-29
        相关资源
        最近更新 更多