【问题标题】:uint8_t VS uint32_t different behaviouruint8_t VS uint32_t 不同的行为
【发布时间】:2016-08-17 20:42:38
【问题描述】:

我目前正在处理需要使用 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)0 等价于~(int)(DIGIT_T)0,或者只是~0。根据 C 和 C++ 的规则,算术和按位运算符的参数受到整数提升的影响。见Integral promotion paragraph
  • 整数提升规则意味着如果DIGIT_T 支持的范围小于int,则~(DIGIT_T)0 等价于~(int)0
  • 贴出的代码是C++ 不是C 请去掉c 标签
  • 嗯,输出的值要么是(每个发布的代码)32 位值,要么是(第一个 #define 未注释)8 位值。所以自然生成的输出是 32 位或 8 位。
  • @user3629249 我在 C 代码中遇到了问题,这只是一个快速的 sn-p 代码来呈现问题 :)

标签: c++ type-conversion


【解决方案1】:

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

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

当然可以简写为:

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

Live demo

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-04-10
    • 2014-07-23
    • 2017-06-13
    • 1970-01-01
    • 1970-01-01
    • 2020-04-15
    • 2013-11-15
    • 2017-01-16
    相关资源
    最近更新 更多