c ++ - 警告:右移计数> = 32位机器上的类型宽度

ida*_*hmu 3 c++ bit-shift 32bit-64bit unsigned-integer

我有以下功能:

void func(unsigned long v)
{
  char max_byte = 0xFF;
  char buffer[8];

  buffer[0] = static_cast<char>((v)       & max_byte);
  buffer[1] = static_cast<char>((v >> 8)  & max_byte);
  buffer[2] = static_cast<char>((v >> 16) & max_byte);
  buffer[3] = static_cast<char>((v >> 24) & max_byte);
  buffer[4] = static_cast<char>((v >> 32) & max_byte);
  buffer[5] = static_cast<char>((v >> 40) & max_byte);
  buffer[6] = static_cast<char>((v >> 48) & max_byte);
  buffer[7] = static_cast<char>((v >> 56) & max_byte);
}
Run Code Online (Sandbox Code Playgroud)

它接受一个unsigned long参数并将其8个字节插入char缓冲区(不要试图找出原因.它是一个有意义的函数的简洁版本).

此代码在64位上编译良好,但在32位上我得到以下警告:

warning: right shift count >= width of type
Run Code Online (Sandbox Code Playgroud)

指线:

  buffer[4] = static_cast<char>((v >> 32) & max_byte);
  buffer[5] = static_cast<char>((v >> 40) & max_byte);
  buffer[6] = static_cast<char>((v >> 48) & max_byte);
  buffer[7] = static_cast<char>((v >> 56) & max_byte);
Run Code Online (Sandbox Code Playgroud)

我想我理解这个警告,但我不知道我该怎么办才能在32位上顺利编译它.

eca*_*mur 8

使用固定宽度的整数类型.在这种情况下,你想要std::uint64_t.


Dan*_*vil 5

unsigned long只保证有32位.看到这里.你需要使用unsigned long long64位保证.

更好的是使用固定宽度的整数,即uint64_t.它们在标题<cstdint>(或<stdint.h>)中定义.