我不明白这段代码的输出:
main() {
int ret = ~(~0 <<5) << 2;
printf("ret: %d, %u\n", ret, ret);
}
output:
ret: 124, 124
如果我在精神上处理,我会这样做:
我做错了什么?
答案 0 :(得分:1)
if int is 4 bytes then:
~0 = 11111111111111111111111111111111 = -1
-1 << 5 = 11111111111111111111111111100000 = -32
~-32 = 00000000000000000000000000011111 = 31
31 << 2 = 11111111111111111111111000000000 = 124
if int is 2 bytes then:
~0 = 1111111111111111 = 65535
65535 << 5= 1111111111100000 = 65504
~65504 = 0000000000011111 = 31
31 << 2 = 0000000001111100 = 124
int is guaranteed to be able to hold -32767 to 32767,
which requires 16 bits.
In that case, int , is 2 bytes.
However, implementations are free to go beyond that minimum,
as you will see that many modern compilers make int 32-bit
(which also means 4 bytes pretty ubiquitously).
答案 1 :(得分:0)
~0是二进制的全1。
左移5,将有5 0,然后全1。
〜这是5 1;这是31。
左移2位等于乘以4,留下124作为最终答案。