【发布时间】:2014-05-09 14:56:02
【问题描述】:
我有以下功能:
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);
}
它接受一个unsigned long 参数并将其8 个字节插入char 缓冲区(不要试图找出原因。它是一个有意义的函数的简明版本)。
此代码在 64 位上编译良好,但在 32 位上我收到以下警告:
warning: right shift count >= width of type
指行:
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);
我想我理解了这个警告,但我不确定我应该怎么做才能在 32 位上顺利编译它。
【问题讨论】:
-
是的,是undefined behavior执行宽度大于或等于位数的移位。
-
unsigned long在 32 位系统上的长度是多少? -
@ShafikYaghmour 我明白,但解决方案是什么。
unsigned long长度为 64 位,我需要正确处理。 -
让我们谈谈轮班运算符 > - viva64.com/en/b/0142
标签: c++ 32bit-64bit bit-shift unsigned-integer