为什么将0xff左移24位会导致值不正确? [英] Why does shifting 0xff left by 24 bits result in an incorrect value?
问题描述
我想将0xff
左移3个字节,并将其存储在uint64_t
中,它应该这样工作:
I would like to shift 0xff
left by 3 bytes and store it in a uint64_t
, which should work as such:
uint64_t temp = 0xff << 24;
这产生的值0xffffffffff000000
绝对不是预期的0xff000000
.
This yields a value of 0xffffffffff000000
which is most definitely not the expected 0xff000000
.
但是,如果我将其移位少于3个字节,则会得到正确的答案.
However, if I shift it by fewer than 3 bytes, it results in the correct answer.
此外,尝试将0x01左移3个字节确实有效.
Furthermore, trying to shift 0x01 left by 3 bytes does work.
这是我的输出:
0xff shifted by 0 bytes: 0xff
0x01 shifted by 0 bytes: 0x1
0xff shifted by 1 bytes: 0xff00
0x01 shifted by 1 bytes: 0x100
0xff shifted by 2 bytes: 0xff0000
0x01 shifted by 2 bytes: 0x10000
0xff shifted by 3 bytes: 0xffffffffff000000
0x01 shifted by 3 bytes: 0x1000000
经过一些实验,每个uint64_t的左移操作最多3位,直到0x7f,这产生0x7f000000. 0x80会产生0xffffffff80000000.
With some experimentation, left shifting works up to 3 bits for each uint64_t up to 0x7f, which yields 0x7f000000. 0x80 yields 0xffffffff80000000.
有人对此异常行为有解释吗? 0xff000000当然属于uint64_t的2 64 -1个限制.
Does anyone have an explanation for this bizarre behavior? 0xff000000 certainly falls within the 264 - 1 limits of uint64_t.
推荐答案
我怀疑该行为与编译器相关,但是我看到的是同一件事.
I suspect the behavior is compiler dependent, but I am seeing the same thing.
修复很简单.在执行移位之前,请确保将0xff强制转换为uint64_t类型.这样,编译器会将其作为正确的类型进行处理.
The fix is simple. Be sure to cast the 0xff to a uint64_t type BEFORE performing the shift. That way the compiler will handle it as the correct type.
uint64_t temp = uint64_t(0xff) << 24
这篇关于为什么将0xff左移24位会导致值不正确?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!