简体   繁体   中英

uint8_t VS uint32_t different behaviour

I am currently working on project where I need to use uint8_t. I have found one problem, could someone explain to me why this happens ?

//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 is as expected

ffffffff
7fffffff

but when I uncomment the first line and I use uint8_t the output is

ff
ff

This behaviour is causing me troubles.

Thank you for your help.

Marek

As the comments already explained in details, this is caused by integer promotion. This should do the trick:

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

which can of course be shortened to:

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

Live demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM