二进制补码和fmt.Printf [英] Two's complement and fmt.Printf
问题描述
因此,计算机使用二进制补码在内部表示带符号的整数.即-5表示为^ 5 +1 ="1111 1011".
So computers use Two's complement to internally represent signed integers. I.e., -5 is represented as ^5 + 1 = "1111 1011".
但是,尝试打印二进制表示形式,例如以下代码:
However, trying to print the binary representation, e.g. the following code:
var i int8 = -5
fmt.Printf("%b", i)
输出 -101
.不完全是我所期望的.格式是否不同?还是不使用二进制补码?
Outputs -101
. Not quite what I'd expect. Is the formatting different or is it not using Two's complement after all?
有趣的是,转换为无符号int会导致正确"位模式:
Interestingly, converting to an unsigned int results in the "correct" bit pattern:
var u uint8 = uint(i)
fmt.Printf("%b", u)
输出为 11111011
-恰好是 -5
的2s补码.
Output is 11111011
- exactly the 2s complement of -5
.
所以在我看来,该值实际上是在内部使用Two's补码的格式,但是格式是打印未签名的 5
并在-
前面.
So it seems to me the value is internally the really using Two's complement, but the formatting is printing the unsigned 5
and prepending a -
.
有人可以澄清吗?
推荐答案
我相信答案在于 fmt
模块如何格式化二进制数字,而不是内部格式.
I believe the answer lies in how the fmt
module formats binary numbers, rather than the internal format.
如果您查看 fmt.integer
,该函数首先执行的操作之一就是将负有符号整数转换为正整数:
If you take a look at fmt.integer
, one of the very first actions that the function does is to convert the negative signed integer to a positive one:
165 negative := signedness == signed && a < 0
166 if negative {
167 a = -a
168 }
There's then logic to append -
in front of the string that's output here.
IOW -101
实际上是将-
二进制附加到 5
上.
IOW -101
really is -
appended to 5
in binary.
注意: fmt.integer
是从 pp.printArg
在同一函数中调用的.
Note: fmt.integer
is called from pp.fmtInt64
in print.go, itself called from pp.printArg
in the same function.
这篇关于二进制补码和fmt.Printf的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!