is it possible to convert bitset<8> to an array of characters of integers?

非 Y 不嫁゛ 提交于 2019-12-20 04:59:10

问题


I have bitset<8> v8 and its value is something like "11001101", something in binary, how can we convert it to an array of characters or integers in c++?


回答1:


To convert to an array of char, you could use the bitset::to_string() function to obtain the string representation and then copy individual characters from that 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';
}



回答2:


vector<int> ints;
for(int i = 0 ; i < v8.size() ; i++ )
{
     ints.push_back(v8[i]);
}

Likewise, you can make an array of chars. Or you may use raw array as:

char chars[8];
for(int i = 0 ; i < v8.size() ; i++ )
{
     chars[i] = v8[i];
}


来源:https://stackoverflow.com/questions/5005863/is-it-possible-to-convert-bitset8-to-an-array-of-characters-of-integers

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!