代码之家  ›  专栏  ›  技术社区  ›  CsgoTalks Com

Unt8+t C++中的字符串向量

  •  0
  • CsgoTalks Com  · 技术社区  · 6 年前

    我有一个向量 带字符串 它表示如下位:

    string str1[] = { "0b01100101", "0b01100101", "0b01011101", "0b11001111"}
    

    我需要精确的值加在一个uint8位向量上:

    uint8_t str2[] = { 0b01100101, 0b01100101, 0b01011101, 0b11001111}
    

    最终结果应该和上面的完全一样。 如果有人知道我该怎么做,我会感激的。

    2 回复  |  直到 6 年前
        1
  •  2
  •   Maxim Egorushkin    6 年前

    不幸的是,没有标准函数来解析前缀为“0b”的二进制字符串。

    你可以雇佣老好人 std::strtoul (1个电话线 STD:斯特劳特 以及5行错误检查):

    #include <algorithm>
    #include <stdexcept>
    #include <cstdlib>
    #include <string>
    
    uint8_t binary_string_to_uint8(std::string const& s) {
        if(s.size() != 10 || '0' != s[0] || 'b' != s[1])
            throw std::runtime_error("Invalid bit string format: " + s);
        char* end = 0;
        auto n = std::strtoul(s.c_str() + 2, &end, 2);
        if(end != s.c_str() + s.size())
            throw std::runtime_error("Invalid bit string format: " + s);
        return n;
    }
    
    int main() {
        std::string str1[] = { "0b01100001", "0b01100101", "0b01011101", "0b11001111"};
        uint8_t str2[sizeof str1 / sizeof *str1];
        std::transform(std::begin(str1), std::end(str1), std::begin(str2), binary_string_to_uint8);
    }
    
        2
  •  0
  •   ricco19    6 年前

    请注意,这些可能会输出与算法几乎相同或相同的程序集,因此类似于另一个答案的算法几乎总是首选的。尽管如此,这里还有一些使用循环的选项:

    std::stoul -至少需要C++ 11。我们这里也没有边界检查,我们假设所有字符串都是 >= 2号。

    std::string str1[] = {"0b01100101", "0b01100101", "0b01011101", "0b11001111"};
    const size_t sz = sizeof str1 / sizeof *str1;
    uint8_t str2[sz];
    for (size_t i = 0; i < sz; ++i)
        str2[i] = static_cast<uint8_t>(std::stoul(&str1[i][2], nullptr, 2));
    

    因为实际上,这些最有可能是可变大小的数组,所以最好使用 vector 在此处键入。

    std::vector<std::string> vs;
    // add a bunch of stuff to vs
    ...
    
    std::vector<uint8_t> vi;
    vi.reserve(vs.size());
    for (const auto &s : vs)
        vi.push_back(static_cast<uint8_t>(std::stoul(&s[2], nullptr, 2)));