从 64 位整数中提取 32 位

Gab*_*iel 2 c++ type-conversion c++11

我有一个uint64_t 整数,并uint32_t通过以下代码将最后 32 位提取为一个数字:

uint32_t getLast(uint64_t v){
      uint64_t t= v >> 32;
      return  reinterpret_cast<uint32_t &>( t ); // type-punned pointer warning
}

int main()
{
    uint64_t a = 1l << 33 | 1l << 3;
    std::cout << getLast(a) << std::endl; // prints 2
}
Run Code Online (Sandbox Code Playgroud)

此代码给出警告:

warning: dereferencing type-punned pointer will break strict-aliasing rules [-Wstrict-aliasing]
       return  reinterpret_cast<uint32_t &>( t );
Run Code Online (Sandbox Code Playgroud)

我想解决这个问题,但不是通过使用联合类型。

reinterprete_cast给未定义的行为,访问数据(复制重新诠释的东西进入返回值)时,(我想?)

另一个似乎有效的解决方案?

 uint32_t getLast(uint64_t v){

    return (v >> 32) // conversion from bitshifted 64bit to 32bit, but what is with overflow?
 }
Run Code Online (Sandbox Code Playgroud)

我有点困惑,关于 reinterpret_cast 的未定义行为?那么我应该如何使用reinterpret_cast,我认为这个例子是典型的使用模式?第二种方法也能安全工作吗?

Pup*_*ppy 5

你应该只是static_cast<uint32_t>. reinterpret_cast几乎专门用于高度狡猾且可能非法的指针转换。