gpt4 book ai didi

c - 带符号 int 的位移位重置过多

转载 作者:行者123 更新时间:2023-12-03 16:46:27 25 4
gpt4 key购买 nike

请看下面的代码片段,它基本上只是向左移动 1 个字节 24 位。

uint64_t i = 0xFFFFFFFF00000000;
printf("before: %016llX \n", i);
i += 0xFF << 24;
printf("after : %016llX \n", i);

// gives:
// before: FFFFFFFF00000000
// after : FFFFFFFEFF000000
最高有效的 32 位是 FFFFFFFE (观看 E 最后)。这并不像我预期的那样。我不明白为什么左移 1 个字节 24 位会触及第 32 位(第 31 位应该是最后修改的)它改变了最后一个 F ( 1111 ) 变成 E ( 1110 ))。
为了使其正常工作,我使用了 0xFF无符号( ​​ 0xFFU )。
uint64_t i = 0xFFFFFFFF00000000;
printf("before: %016llX \n", i);
i += 0xFFU << 24;
printf("after : %016llX \n", i);

// gives:
// before: FFFFFFFF00000000
// after : FFFFFFFFFF000000
为什么带符号整数( 0xFF )的位移位会过多地触摸/重置一位?

最佳答案

你左移到符号位。
整数常量 0xFF有类型 int .假设 int是 32 位,表达式 0xFF << 24将设置为 1 的位移入有符号整数触发器的高位 undefined behavior在您的情况下,这表现为意外值。
这在 C standard 的第 6.5.7p4 节中有详细说明。 :

The result of E1 << E2 is E1 left-shifted E2 bit positions; vacated bits are filled with zeros. If E1 has an unsigned type, the value of the result is E1×2E2, reduced modulo one more than the maximum value representable in the result type. If E1 has a signed type and nonnegative value, and E1×2E2is representable in the result type, then that is the resulting value; otherwise, the behavior is undefined.


通过使用 U后缀这使常量具有类型 unsigned int , 将设置为 1 的位移入高位是有效的,因为没有符号位。

关于c - 带符号 int 的位移位重置过多,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67182280/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com