c++ - 字符串 vector 到 uint8_t C++

标签 c++ string bit

我有一个 vector 带有表示位的字符串,如下所示:

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

我需要添加到 uint8_t 位 vector 的确切值:

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

最终结果应该与上面完全一样。 如果有人知道我该怎么做,我将不胜感激。

最佳答案

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

你可以雇佣老好人std::strtoul (1 行调用 std::strtoul 和 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);
}

关于c++ - 字符串 vector 到 uint8_t C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50494270/

相关文章:

c++ - some_struct* args1 = (some_struct*)args2

Java 正则表达式从字符串中拆分 double

java - 将字符串存储到包含出现次数的哈希表中

C++ valgrind 可能在 STL 字符串上泄漏

mysql - 在 Laravel 中存储 32 位二进制文​​件的正确方法

c++ - 非类型模板参数的偏特化如何工作?

c++ - 调整大小std::vector <std::unique_ptr <T >>的性能

c++ - 我已经阅读了很多有关2d数组的信息,但是在分配作业时遇到了麻烦

c - 有没有办法绕过 C 中的编译器优化?

c - 在二进制中,从有符号数转换为二进制补码。全部在 C 中