我有bitset<8> v8
它的值类似于“11001101”,是二进制的,我们如何在 C++ 中将它转换为字符数组或整数?
最佳答案
要转换为 char 数组,您可以使用 bitset::to_string()
函数获取字符串表示形式,然后从该字符串中复制单个字符:
#include <iostream>
#include <algorithm>
#include <string>
#include <bitset>
int main()
{
std::bitset<8> v8 = 0xcd;
std::string v8_str = v8.to_string();
std::cout << "string form: " << v8_str << '\n';
char a[9] = {0};
std::copy(v8_str.begin(), v8_str.end(), a);
// or even strcpy(a, v8_str.c_str());
std::cout << "array form: " << a << '\n';
}
关于c++ - 是否可以将 bitset<8> 转换为整数字符数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5005863/