【问题标题】:Implicit type conversion for bitwise operation按位运算的隐式类型转换
【发布时间】:2020-07-09 15:34:05
【问题描述】:

我有这个操作:

uint32_t DIM = // ...
int32_t x = // ...

// Operation:
x & (DIM-1u)

语句x & (DIM-1u)中的隐式类型转换是如何工作的?

  • 它是否将x 转换为uint32_t
  • (DIM-1u)int32_t
  • 另外,结果类型是什么?是uint32_t 还是int32_t

【问题讨论】:

标签: c++ type-conversion bitwise-operators


【解决方案1】:

两种情况,注意1uunsigned 类型的文字:

  1. unsigned 在 16 位到 31 位的范围内。 DIM - 1u的类型为uint32_t,整个表达式为uint32_t。这是因为二进制表达式中的 signed 类型(其中另一个参数是 unsigned 类型)被隐式转换为 unsigned

  2. unsigned 为 32 位或更大。那么DIM - 1u的类型就是unsigned,整个表达式的类型也一样。


最后请注意,C++ 标准允许unsignedstd::uint32_t 是同一类型;即

std::cout << std::is_same<std::uint32_t, unsigned>::value;

允许为 1。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-04
    • 2021-06-16
    相关资源
    最近更新 更多