c - 为什么此代码片段的输出为 -33

标签 c bit-manipulation code-snippets

#include<stdio.h>

int main()
{
    int a=32;
    printf("%d\n", ~a);  //line 2
    return 0;
}

o/p = -33

实际上,在原始代码片段中,第 2 行是

 printf("%x\n", ~a);  //line 2

我解决了它就像

32 in hex is 20.
0000 0000 0010 0000
now tilde operator complements it
1111 1111 1101 1111 = ffdf.

当我遇到问题时,我很困惑如何解决

printf("%d\n", ~a);  //line 2 i.e %d NOT %x.

最佳答案

在 C 实现中,与任何编程语言的大多数现代实现一样,有符号整数用 two’s complement 表示。 .

在二进制补码中,高位表示负数,值的编码方式如下示例所示:

Bits  Decimal
0…011 +3
0…010 +2
0…001 +1
0…000  0
1…111 -1
1…110 -2
1…101 -3

因此,如果位的常用(无符号)二进制值为 n 并且高位为零,则表示的值为 +n。但是,如果高位为 1,则表示的值为 n-2w,其中 w 为宽度(格式中的位数)。

因此,在无符号 32 位格式中,32 位通常为 4,294,967,295。在二进制补码 32 位格式中,32 个一位为 4,294,967,295 - 232 = -1。

在您的情况下,您拥有的位是 1111 1111 1111 1111 1111 1111 1101 1111。在无符号 32 位格式中,即 4,294,967,263。以二进制补码表示,为 4,294,967,263 - 232 = -33。

关于c - 为什么此代码片段的输出为 -33,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20668437/

相关文章:

c - HAL_Delay() 陷入死循环

c++ - 我怎样才能有效地洗牌?

java - 如何将 32 位 int 移位 32(再次)

c - C语言如何使用Bitwise提取页码和偏移量

xcode - 自定义 Xcode 片段库

scope - 定义自定义 Sublime Text 2 片段的范围

html - 在 HTML 中插入代码片段

c - `nm` 输出符号未被 `LC_SYMTAB` 引用

c - 我如何询问论据?

c - error : stdio. h: No such file or directory error during make