gpt4 book ai didi

c++ - uint8_t VS uint32_t 不同的行为

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:47:09 28 4
gpt4 key购买 nike

我目前正在从事需要使用 uint8_t 的项目。我发现了一个问题,有人可以向我解释为什么会这样吗?

//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;

在这种情况下,输出符合预期

ffffffff
7fffffff

但是当我取消注释第一行并使用 uint8_t 时,输出是

ff
ff

这种行为给我带来了麻烦。

感谢您的帮助。

马立克

最佳答案

正如评论中已经详细解释的那样,这是由整数提升引起的。这应该可以解决问题:

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

当然可以缩短为:

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

Live demo

关于c++ - uint8_t VS uint32_t 不同的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36823951/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com