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++?
Asked
Active
Viewed 7,116 times
1

bijlikamasla
- 371
- 3
- 6
- 11
-
How do you want `11001101` to be interpreted? each digit as one char (and one int)? – Nawaz Feb 15 '11 at 15:49
-
each digit as one character, because i want to make a matrix, for that i will need each as a character – bijlikamasla Feb 15 '11 at 15:51
2 Answers
1
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];
}

Nawaz
- 353,942
- 115
- 666
- 851
-
thanks, but if I use cout to display them, it doesnt gives correct answer – bijlikamasla Feb 15 '11 at 16:05
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';
}

Cubbi
- 46,567
- 13
- 103
- 169