gpt4 book ai didi

c - 按位和超过 32 位

转载 作者:行者123 更新时间:2023-12-05 09:07:32 27 4
gpt4 key购买 nike

#include <stdio.h>
#include <limits.h>

int main()
{
unsigned long long a = 9223372036854775808; // a = 2^63
a = a & ~1;
printf("%llu\n", a);
printf("%d, %lld", INT_MAX, LLONG_MAX);
}

输出

9223372036854775808
2147483647, 9223372036854775807

这是 C17 中 ~ 的语义(粗体),6.5.3.3.4。

The result of the ~ operator is the bitwise complement of its (promoted) operand (that is, each bit inthe result is set if and only if the corresponding bit in the converted operand is not set). The integerpromotions are performed on the operand, and the result has the promoted type. If the promotedtype is an unsigned type, the expression ~E is equivalent to the maximum value representable inthat type minus E.

这是 C17 6.5.10.3 中一元 & 的语义。

The usual arithmetic conversions are performed on the operands.

a 等于 9223372036854775808 等于 8000 0000 0000 0000(16)

没有任何后缀的整数常量1 等同于(int)1。因此 ~1 == ~(int)1 == FFFF FFFE(16)( 不会进行整数提升~ )。

FFFF FFFE(16)的类型在
转换为unsigned long longa = 8000 0000 0000 0000(16) & FFFF FFFE(16) 通过通常的算术转换。因此
a = 8000 0000 0000 0000(16) & FFFF FFFE(16) ==
a = 8000 0000 0000 0000(16) & 0000 0000 FFFF FFFE(16)

最后,
a = a & ~1 ==
a = 8000 0000 0000 0000(16) & FFFF FFFE(16) ==
a = 8000 0000 0000 0000(16) & 0000 0000 FFFF FFFE(16) ==
a = 0000 0000 0000 0000(16)

但是输出好像是
a = a & ~1 ==
a = 8000 0000 0000 0000(16) & FFFF FFFE(16) ==
a = 8000 0000 0000 0000(16) & FFFF FFFF FFFF FFFE(16) ==
a = 8000 0000 0000 0000(16)

我的问题是输出是如何显示的?

最佳答案

~1 在二进制补码系统(所有现代系统 - 包括您的 PC 使用它)中是 -2

-2 在 4 字节长整数中的二进制表示是 0xfffffffe

当您将其提升为 long long integer 时,值 -2 会保留,但二进制表示会更改:0xfffffffffffffffffe。此值是二进制 AND - 与您的变量 a - 因此其值保持不变。

如果你想阻止这种行为,你需要告诉编译器你想使用什么大小的数据:

    a = a & ~(unsigned)1;

它会像你期望的那样运行

https://godbolt.org/z/G6757W

关于c - 按位和超过 32 位,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64766192/

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