2's Complement in base 2 output of fmt

566 views
Skip to first unread message

ni....@gmail.com

unread,
Jul 9, 2015, 5:10:23 AM7/9/15
to golan...@googlegroups.com
Hello all,

I understand that "%b" handles signed int without regards of  2's complement, while I personally do not have requirement to use 2's complement output using fmt, I'm curious at the rationale as to not making 2'complement the default output form for "%b" on negative integers. 

src/fmt/fmt_test.go L: 313
   313		{"%b", -6, "-110"},
src/fmt/format.go L:179-181
   179		if negative {
   180			a = -a
   181		}


BR,
Nils

Rob Pike

unread,
Jul 9, 2015, 6:02:53 AM7/9/15
to Ersi Ni, golan...@googlegroups.com
If you want to print an unsigned number, you must make the number unsigned.

package main

import "fmt"

func main() {
  x := -6
  fmt.Printf("%b", uint(x))
}

output: 11111111111111111111111111111010

Why is that not the default? Because if it were, there would be no way to print something as a negative number, which as you can see is a much shorter representation. Or to put it another way, %b %o %d %x all treat their arguments identically.


--
You received this message because you are subscribed to the Google Groups "golang-dev" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-dev+...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

ni....@gmail.com

unread,
Jul 9, 2015, 6:29:05 AM7/9/15
to golan...@googlegroups.com, ni....@gmail.com
Thank you for the detailed explanation. Indeed this is the uniformed "fmt" way. It makes a lot of sense.
Reply all
Reply to author
Forward
0 new messages