【问题标题】:Store multiple hex values in a string c++在字符串c ++中存储多个十六进制值
【发布时间】:2023-04-02 10:10:01
【问题描述】:

我想将整数数组转换为十六进制形式,然后将所有十六进制值连接成一个 C++ 字符串。整数最初是uint8_t,但我读到了如何毫无问题地将它们转换为int。到目前为止,我有这个。

for (int i = 0; i < HASHLEN; ++i) {
  int a = static_cast< int >(hash2[i]); // convert the uint8_t to a int
  cout << setfill('0') << setw(2) << hex << a; // print the hex value with the leading zero (important)
}

此代码将数组中每个 int 的十六进制值打印在一行上,如下所示:

41a9ffb9588717989367b3ec942233d5d9a982f8658c1073a87262da43fd42c9

如何将此值存储为字符串?我尝试在循环之前创建一个string hash = ""; 并使用这一行:

hash = hash + to_string(setfill('0') + setw(2) + hex + a);

而不是cout 行,但这不起作用。如果你想知道,错误是

error: invalid operands to binary expression ('__iom_t4&lt;char&gt;' and 'std::__1::__iom_t6')

【问题讨论】:

    标签: c++


    【解决方案1】:

    std::stringstream 替换cout 就可以了:

    std::stringstream hexstr;
    for (int i = 0; i < HASHLEN; ++i) {
        int a = static_cast< int >(hash2[i]);
        hexstr << setfill('0') << setw(2) << hex << a;
    }
    std::string res = hexstr.str();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-03-27
      • 2019-07-22
      • 2020-06-15
      • 2019-07-27
      • 2017-08-07
      • 1970-01-01
      • 2019-10-12
      • 2018-01-31
      相关资源
      最近更新 更多