Uint8_t VS uint32_t different behavior

I am currently working on a project where I need to use uint8_t. I found one problem, can someone explain to me why this is happening?

//using DIGIT_T = std::uint8_t; using DIGIT_T = std::uint32_t; std::uint8_t bits = 1; DIGIT_T test1 = ~(DIGIT_T)0; std::cout << std::hex << (std::uint64_t)test1 << std::endl; DIGIT_T test2 = ((~(DIGIT_T)0) >> bits); std::cout << std::hex << (std::uint64_t)test2 << std::endl; 

in this case, the output will be as expected

 ffffffff 7fffffff 

but when i uncomment the first line and i use uint8_t, the output will be

 ff ff 

This behavior is causing me problems.

Thank you for your help.

Marek

+5
source share
1 answer

As the comments have already explained in detail, this is due to the whole promotion. This should do the trick:

 DIGIT_T test2 = ((DIGIT_T)(~(DIGIT_T)0) >> bits); 

which, of course, can be shortened to:

 DIGIT_T test2 = (DIGIT_T)~0 >> bits; 

Live demo

+1
source

Source: https://habr.com/ru/post/1247815/


All Articles