Passing bits to unsigned char and vice versa

Working with unsigned char arrays representing bits. I came across the following. On MSVC 2013, output std::bitset<8>

to char and back. This seems to be the right thing to do.

However, in the ISO C ++ 11 standard. I was unable to find a reference to this. From what I was able to collect, std::bitset

it is just an array bool

. With a more economical memory implementation and some features surrounding it.

In short, my question is, is the code below valid.

unsigned char* myChar = new unsigned char(0x0F);

std::cout << "expression result:" << (uint8_t)*myChar;



source to share

1 answer

This behavior is undefined. The standard simply states that

The template class bitset<N>

describes the object that can store a sequence consisting of a fixed number of bits N


It doesn't say anything about the layout of this class inside. There is no guarantee that sizeof(bitset<8>)


. According to my implementation, it happens 8

. So any guess you make about the internals of this class is just a guess. If you want to convert unsigned char

to bitset<8>

, this is already an easy way to do it:

unsigned char myChar = 0x0F;
std::bitset<8> bs(myChar);




All Articles