c - 整数文字的类型和 C 中的 ~

标签 c integer bitwise-operators literals

我是 C 初学者,我对 C 答案书中的以下示例感到困惑。

在您的系统上查找 unsigned long long 大小的一种方法是键入:

printf("%llu", (unsigned long long) ~0);

我不知道为什么这个语法有效?

在我的系统上,int是32位,long long是64位。
我期望的是,由于 0 是整数类型的常量,~0 计算 32 位整数的否定,然后将其转换为 unsigned long long 由转换运算符。结果应该是 232 - 1。

不知何故,~ 运算符似乎已经知道它应该作用于 64 位?
编译器是否将此指令解释为 printf("%llu", ~(unsigned long long)0); ?这听起来不对,因为转换和 ~ 具有相同的优先级。

最佳答案

Somehow, it looks like the ~ operator already knows that it should act on 64 bits?

这不是 ~ 运算符,而是强制转换。以下是根据标准完成整数转换的方式:

6.3.1.3 Signed and unsigned integers

  • When a value with integer type is converted to another integer type other than _Bool, if the value can be represented by the new type, it is unchanged.
  • Otherwise, if the new type is unsigned, the value is converted by repeatedly adding or subtracting one more than the maximum value that can be represented in the new type until the value is in the range of the new type.
  • Otherwise, the new type is signed and the value cannot be represented in it; either the result is implementation-defined or an implementation-defined signal is raised.

signed int ~0 的值对应于系统上的 -1,负值的二进制补码表示。它不能用 unsigned long long 表示,因此第一个要点不适用。

第二个要点确实适用:新类型是无符号的,因此 unsigned long longMAX 被添加到 -1 一次以将结果放入 unsigned long long 的范围内。这与将 -1 符号扩展到 64 位具有相同的效果。

关于c - 整数文字的类型和 C 中的 ~,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28544708/

相关文章:

gedit中c结构的自定义文本颜色

使用 gets 函数时代码块停止工作

c - 如何在C语言中读取特定单词后读取整个句子

c - 使用二进制补码的按位减法溢出

c - 使用给定的按位运算符来重现函数

c - 我怎样才能在 FreeBSD 系统调用 openat 中获得绝对路径?

c - 如何在C中显示十六进制数?

c - 在 C 中通过命令行传递整数?

c - Prime 与否 Prime 输出慢

ios - 如何在 Swift 中创建 NS_OPTIONS 风格的位掩码枚举?