Golang: two add-ons and fmt.Printf

So, computers use two additions for the internal representation of integers. Ie -5 appears as ^ 5 + 1 = "1111 1011".

However, trying to print a binary representation, for example. following code:

var i int8 = -5 fmt.Printf("%b", i) 

Conclusion -101 . Not quite what I expect. Is formatting different or is it using two additions?

Interestingly, converting to unsigned int results in a β€œcorrect” bit pattern:

 var u uint8 = uint(i) fmt.Printf("%b", u) 

Conclusion 11111011 is exactly the complement of 2s to -5 .

So, it seems to me that the value inside really uses two additions, but formatting prints unsigned 5 and adds - .

Can anyone clarify this?

+7
go
source share
1 answer

I believe the answer is how the fmt module forms binary numbers, not the internal format.

If you look at fmt.integer , one of the first things the function does is convert a signed signed integer to a positive integer:

  165 negative := signedness == signed && a < 0 166 if negative { 167 a = -a 168 } 

Then follows the logic of adding - before the line that displays here .

IOW -101 really - added to 5 in binary format.

Note: fmt.integer is called from pp.fmtInt64 in print.go , itself called from pp.printArg in the same function.

+5
source share

All Articles