gpt4 book ai didi

c - 为什么这个shift插入1s呢? C

转载 作者:行者123 更新时间:2023-11-30 20:09:24 25 4
gpt4 key购买 nike

我正在尝试创建一个 32 位二进制文​​件,除了 srt 以外全为 0,以 1 结尾。因此,如果 srt 是 2 并且 end 是 7,我会得到 00000000 00000000 00000001 11111100。当我进行第二次转变时,它会给出更多的 1 而不是零,我不知道为什么。非常了解C和位操作,如果有人能解释我将非常感激。

int groupOne(int srt, int end){
int mask =-1;
int ret;
ret = 1<<end;
ret=ret<<srt;

ret = mask+ret;
return ret;
}

最佳答案

摘自 C 委员会草案 (N1570):

6.5.7 Bitwise shift operators
...
Semantics
3 The integer promotions are performed on each of the operands. The type of the result is that of the promoted left operand. If the value of the right operand is negative or is greater than or equal to the width of the promoted left operand, the behavior is undefined.

4 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 (2 power E2), reduced modulo one more than the maximum value representable in the result type. If E1 has a signed type and nonnegative value, and E1 × 2E2 (2 power E2) is representable in the result type, then that is the resulting value; otherwise, the behavior is undefined.

5 The result of E1 >> E2 is E1 right-shifted E2 bit positions. If E1 has an unsigned type or if E1 has a signed type and a nonnegative value, the value of the result is the integral part of the quotient of E1 / 2E2 (2 power E2). If E1 has a signed type and a negative value, the resulting value is implementation-defined.

关于c - 为什么这个shift插入1s呢? C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52639273/

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