Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Casting a bitset to unsigned char, and vice versa

Working with unsigned char arrays, representing bits. I came across the following. On MSVC 2013 casting an std::bitset<8> to a char, and back. Seems to be a valid thing to do.

However in the C++11 ISO standard. I wasn't able to find a reference of this being valid. From what I have been able to gather, an std::bitset is merely is a bool array. With a more memory economic implementation and some functions surrounding it.

So in short, my question is: Is the code below valid.

unsigned char* myChar = new unsigned char(0x0F);
((std::bitset<8>*)myChar)->set(2);
((std::bitset<8>*)myChar)->reset(6);

std::cout << "expression result:" << (uint8_t)*myChar;
like image 291
laurisvr Avatar asked Sep 28 '22 03:09

laurisvr


1 Answers

This is undefined behavior. The standard merely states that

The class template bitset<N> describes an object that can store a sequence consisting of a fixed number of bits, N.

It says nothing about the layout of this class internally. There is no guarantee that sizeof(bitset<8>) is 1. On my implementation, it happens to be 8. Thus, any assumption you are making about the internals of this class is just that - an assumption. If you want to convert an unsigned char to a bitset<8>, there is already an easy way to do that:

unsigned char myChar = 0x0F;
std::bitset<8> bs(myChar);
like image 51
Barry Avatar answered Oct 09 '22 19:10

Barry