I want to cast an array of bits into a byte, it works by using a loop and bitshift, but I think it would be cost inefective if run repeatedly (I might be wrong). So I wanted to use a pointer with reinterpret_cast.
It works when I use it between uint8_t and uint16_t
uint16_t a = 32769; uint8_t *aPtr = reinterpret_cast<uint8_t*>(&a); std::cout << (int) a << " => {" << (int)*(aPtr) << ", " << (int)*(aPtr + 1) << "}" << std::endl; uint8_t b[2] = {1, 128}; uint16_t *bPtr = reinterpret_cast<uint16_t*>(&b); std::cout << "{" << (int)b[0] << ", " << (int)b[1] << "} => " << (int)*bPtr << std::endl; It gives
32769 => {1, 128} {1, 128} => 32769 But when I try it with bool and uint8_t it won't work
bool c[8] = {1, 1, 1, 1, 1, 1, 1, 1}; uint8_t *cPtr = reinterpret_cast<uint8_t*>(&c); std::cout << "{"; for(int i=0; i<8; i++) std::cout << c[i] << (i < 7 ? ", " : ""); std::cout << "} => " << (int)*cPtr << std::endl; uint8_t d = 255; bool *dPtr = reinterpret_cast<bool*>(&d); std::cout << (int)d << " => {"; for(int i=0; i<8; i++) std::cout << *(dPtr + i) << (i < 7 ? ", " : ""); std::cout << "}" << std::endl; With result
{1, 1, 1, 1, 1, 1, 1, 1} => 1 255 => {255, 1, 1, 1, 1, 1, 1, 1} Is it impossible to do it with reinterpret_cast? or I just do it wrong? or even my guess about loop and bitshift is wrong in the first place?
booloccupies one byte? There are 7 unused zero bits in it.std::bitsetandstd::vector<bool>.std::bitsethas methods which convert to an unsigned integer.std::bitsethas methods which convert to an unsigned integer, however it has a fixed size (fixed but still chosen by you). IF that is not a problem then you should take a look. Judging by your code abovestd::bitset<16> c = ...; uint16_t d = c.to_ulong();seems to be what you want.uint8_t b[2]? Is this what you are callingbool c[8]?