Saj*_*S F 2 c c++ bit-manipulation bit-shift shift
我正在尝试通过组合16位和8位值来填充64位无符号变量:
uint8_t byte0 = 0x00;
uint8_t byte1 = 0xAA;
uint8_t byte2 = 0x00;
uint8_t byte3 = 0xAA;
uint16_t hword0 = 0xAA00;
uint16_t hword1 = 0xAAAA;
uint64_t result = ( hword0 << 32 ) + ( byte3 << 24 ) +
( byte2 << 16 ) + ( byte1 << 8 ) + ( byte0 << 0 );
Run Code Online (Sandbox Code Playgroud)
这给了我一个警告。
Run Code Online (Sandbox Code Playgroud)left shift count >= width of type [-Wshift-count-overflow] uint64_t result = ( hword0 << 32 )
hword0是16位长,您要求32位移位。移位超过位数-1是不确定的。
解决方案是将组件转换为目标类型:uint64_t result = ( ((uint64_t)hword0) << 32 ) +etc。
与您的问题图块相反,您可以将uint16_t. 但你不能(无损地)移动它超过它的宽度。
您的输入操作数的类型也适用于输出操作数,因此在您最初的问题中,您的 auint16_t << 32为 0 (因为任何向左移动 32 位然后剪裁为 16 位的值都是 0),因此几乎所有你的uint8_t价值观。
解决方案很简单:在转换之前,将您的值转换为适合转换的适当类型:
uint64_t result = ( (uint64_t)hword0 << 32 ) +
( (uint32_t)byte3 << 24 ) + ( (uint32_t)byte2 << 16 ) + ( (uint32_t)byte1 << 8 ) + ( (uint32_t)byte0 << 0 );
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1086 次 |
| 最近记录: |