问题描述
我知道我为signed int分配了一个大于其可以处理的值的值。另外,我应该对签名使用%d
,对未签名使用%u
。同样,我不应该将 -ve
的值分配给unsigned。但是,如果我进行如下分配并使用printf,结果将显示如下。
I understand that I am assigning signed int a value that is larger than what it can handle. Also I should be using %d
for signed and %u
for unsigned. Similarly I should not be assigning -ve
value to unsigned. But if I make such assignments and use printf as below, I get the results show below.
我的理解是,在每种情况下,转换成其二的补数的数量二进制表示形式,与 -1
或 4294967295
相同。这就是为什么%u
用于签名打印 4294967295
而忽略 -ve $ c $的原因c>最左边的位。将%d用于带符号的int时,它将最左边的位用作
-ve
标志并打印 -1
。类似地,对于未签名的%u
打印未签名的值,但是%d
会使它将数字视为已签名,从而打印 -1
。
My understanding is that in each case, the number of converted to its two's compliment binary representation which is same for -1
or 4294967295
. That is why %u
for signed prints 4294967295
by ignoring -ve
leftmost bit. When used %d for signed int, it uses left most bit as -ve
flag and prints -1
. Similarly %u
for unsigned prints unsigned value but %d
causes it to treat the number as signed and thus prints -1
. Is that correct?
signed int si = 4294967295;
unsigned int ui = 4294967295;
printf("si = u=%u d=%d\n", si, si);
printf("ui = u=%u d=%d\n", ui, ui);
输出:
si = u=4294967295 d=-1
ui = u=4294967295 d=-1
signed int si = -1;
unsigned int ui = -1;
printf("si = u=%u d=%d\n", si, si);
printf("ui = u=%u d=%d\n", ui, ui);
输出:
si = u=4294967295 d=-1
ui = u=4294967295 d=-1
推荐答案
,则不会忽略最左边或最重要位,并且该位也不为负;而是它的位置值为2 。
In the case of unsigned, the "leftmost" or most significant bit is not ignored, and is not negative; rather it has a place value of 2.
在负数情况下,符号位不是旗;而是位值是-2 。
In the negative case, the sign bit is not a flag; instead it is a bit with a place value of -2.
在两种情况下,整数的值都等于所有二进制数字(位)的位值都设置为1。
In both cases the value of the integer is equal to the sum of the place values of all the binary digits (bits) set to 1.
以这种方式对有符号值进行编码称为 。这不是唯一可能的编码。例如,您所描述的被称为符号和幅度,而另一种可能性是一个人的补语。但是,在实践中很少会遇到这些替代编码,这不仅是因为补码是算术如何在所有硬件上(但可能是最神秘的体系结构)在现代硬件上的工作原理。
The encoding of signed values in this way is known as two's complement. It is not the only possible encoding; what you described is known as sign and magnitude for example, and one's complement is another possibility. However, these alternative encodings are seldom encountered in practice, not least because two's complement is how arithmetic works on modern hardware in all but perhaps the most arcane architectures.
这篇关于未签名和已签名的int和printf的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!