Convert char to bitset?

I need to convert a char to an 8-bit bitset. How should I do this? I tried the following:
1
2
3
4
5
6
7
8
9
10
	bitset<8> ToBits(unsigned char From)
	{
		union //CharBit_t
		{
			bitset<8> Bits;
			unsigned char Char;
		} CharBit;
		CharBit.Char = From;
		return(CharBit.Bits);
	}


But it gives compile errors. Note: this function is in a class.
error C2620: member 'Lypher::ToBits::<unnamed-tag>::Bits' of union 'Lypher::ToBits::<unnamed-tag>' has user-defined constructor or non-trivial default constructor
error C2039: 'Bits' : is not a member of 'Lypher::ToBits::<unnamed-type-CharBit>'
see declaration of 'Lypher::ToBits::<unnamed-type-CharBit>'


How should I do this?
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <iostream>
#include <bitset>
using namespace std;

bitset<8> ToBits(unsigned char byte)
{
    return bitset<8>(byte);
}

int main()
{
    unsigned char byte=1|(1<<3)|(1<<6)|(1<<7);

    bitset<8> my_bset=ToBits(byte);

    cout << my_bset[0];
    cout << my_bset[1];
    cout << my_bset[2];
    cout << my_bset[3];
    cout << my_bset[4];
    cout << my_bset[5];
    cout << my_bset[6];
    cout << my_bset[7] << endl;

    cout << "\nhit enter to quit...";
    cin.get();
}

This might help too -> http://cplusplus.com/reference/stl/bitset/
Last edited on
Huh, I didn't see any mention that I could do it like that when I looked there. Would you tell me where it mentions that?
Last edited on
Well, I guess you were bored to search a bit :P Check the constructor example. You can initialize a bitset with an unsigned long. When you use an unsigned char instead, it is silently converted to an unsigned long.

http://cplusplus.com/reference/stl/bitset/bitset/

EDIT: Come on, people, everything is right under your nose... You just don't see it...
Last edited on
Ahh, thanks! I can't believe I missed that.
Topic archived. No new replies allowed.