简体   繁体   English

uint8_t C的字符串向量

[英]String vector to uint8_t C++

I have a vector with strings that represent bits as follows: 我有一个向量, 其中的字符串表示位,如下所示:

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

and I need the exact values added to a uint8_t bits vector: 我需要将精确值添加到uint8_t位向量中:

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

The end result should look exactly like above. 最终结果应与上面完全一样。 If anyone has any idea how I could do that I would appreciate it. 如果有人知道我该怎么做,我将不胜感激。

There is no standard function to parse binary strings with "0b" prefix, unfortunately. 不幸的是,没有标准函数来解析带有“ 0b”前缀的二进制字符串。

You can employ good old std::strtoul (1 line to call std::strtoul and 5 lines of error checking): 您可以使用旧的std::strtoul (调用std::strtoul 1行和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);
}

Note that these will likely output nearly the same or the same assembly as an algorithm, so an algorithm like in the other answer is almost always preferred. 请注意,它们可能会输出与算法几乎相同或相同的程序集,因此几乎总是首选像其他答案中那样的算法。 Nonetheless, here are a few more options using loops: 尽管如此,这里还有一些使用循环的选项:

std::stoul - at least C++11 required. std::stoul至少需要C ++ 11。 We also do not bounds check here, we assume all strings are >= 2 in size. 我们在这里也没有边界检查,我们假设所有字符串的大小均>= 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));

Since in reality these are most likely going to be variable sized arrays, you may be better off using the actual vector type here. 由于实际上它们很可能是可变大小的数组,因此在这里使用实际的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)));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM