简体   繁体   English

uint8_t VS uint32_t的不同行为

[英]uint8_t VS uint32_t different behaviour

I am currently working on project where I need to use uint8_t. 我目前正在处理需要使用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 但是当我取消注释第一行并使用uint8_t时输出​​为

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 现场演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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