gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 01:33:29 25 4
gpt4 key购买 nike

我有一个 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com