【问题标题】:Convert string representation to byte array [duplicate]将字符串表示形式转换为字节数组[重复]
【发布时间】:2020-07-21 21:55:18
【问题描述】:

用户将从终端输入一个字符串值。我可以用整数表示。但是我需要能够将其转换为字节数组/gsl::span。这可能吗?

#include <string>
#include <iostream>
#include <sstream>

int main()
{
    // integer representation
    std::string s = "0xaabbccdd";
    unsigned int x = std::stoul(s, nullptr, 16);
    std::cout << x << "\n";

    // byte array or gsl::span
    // std::array<uint8_t, 4> val{0xaa, 0xbb, 0xcc, 0xdd};
}

更新可能的解决方案(但使用 std::vector)

#include <vector>
#include <string>
#include <algorithm>
#include <iostream>

std::vector<std::string> split(const std::string & str, int len)
{
    std::vector<std::string> entries;
    for(std::string::const_iterator it(str.begin()); it != str.end();)
    {
        int num = std::min(len,(int)std::distance(it,str.end()));
        entries.push_back(std::string(it,it+num));
        it=it+num;
    };
    return entries;
}

int main() {
    std::string str{"0xaabbccdd"};
     str.erase(0, 2);
    for (auto str : split(str, 2)) {
      std::cout << str << std::endl;
    }
    return 0;
}

【问题讨论】:

  • 我更新了可能的解决方案,但我宁愿避免使用 std::vector

标签: c++ c++11 c++14 std


【解决方案1】:

C++17 及更高版本:std::string::data() 返回可变的 C 字符串表示形式。

旧版 C++:您可以使用 std::string::data 获取字节,但不能保证它是空终止的。您还可以使用std::string::c_str 获取以空字符结尾的字符串。

注意 - 在旧 C++ 中,返回的 C 字符串不保证是可变的(即,它返回 const char *)。据我所知,它始终是可变的,因此您可以抛弃 constness。

【讨论】:

  • 据我所知,它始终是可变的,因此您可以抛弃 constness。 这将导致 未定义的行为。见documentation。引用:“通过非 const 访问路径修改 const 对象并通过非易失性左值引用易失性对象会导致未定义的行为。”
  • 如果数据确实是 const,那么您是对的,但是,它并不是在我所知道的所有实现中。这也是 C++17 明确声明 data() 是可变的原因。
  • 在您的答案中添加相关参考资料会使其更加合理。
猜你喜欢
  • 2011-03-27
  • 1970-01-01
  • 1970-01-01
  • 2012-01-06
  • 2019-12-03
  • 1970-01-01
  • 1970-01-01
  • 2014-07-07
  • 2021-12-01
相关资源
最近更新 更多