go - Golang: Two's complement and fmt.Printf -


so computers use two's complement internally represent signed integers. i.e., -5 represented ^5 + 1 = "1111 1011".

however, trying print binary representation, e.g. following code:

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

outputs -101. not quite i'd expect. formatting different or not using two's complement after all?

interestingly, converting unsigned int results in "correct" bit pattern:

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

output 11111011 - 2s complement of -5.

so seems me value internally using two's complement, formatting printing unsigned 5 , prepending -.

can clarify this?

i believe answer lies in how fmt module formats binary numbers, rather internal format.

if take @ fmt.integer, 1 of first actions function convert negative signed integer positive one:

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

there's logic append - in front of string that's output here.

iow -101 - appended 5 in binary.

note: fmt.integer called pp.fmtint64 in print.go, called pp.printarg in same function.


Popular posts from this blog

php - How should I create my API for mobile applications (Needs Authentication) -

5 Reasons to Blog Anonymously (and 5 Reasons Not To)

Google AdWords and AdSense - A Dynamic Small Business Marketing Duo