我有bitset<8> v8
,它的值类似于“11001101”,是二进制的,我们如何将它转换为 C++ 中的字符或整数数组?
问问题
6348 次
2 回答
2
要转换为 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';
}
于 2011-02-15T16:03:54.593 回答
1
vector<int> ints;
for(int i = 0 ; i < v8.size() ; i++ )
{
ints.push_back(v8[i]);
}
同样,您可以制作一个字符数组。或者您可以将原始数组用作:
char chars[8];
for(int i = 0 ; i < v8.size() ; i++ )
{
chars[i] = v8[i];
}
于 2011-02-15T15:52:41.073 回答