Commit 1ab15fac authored by Andrei Vieru's avatar Andrei Vieru Committed by Rob Pike

fmt format verb %b bug

fmt.Printf("%b", int8(-1)) prints 64 ones instead of 8.
This happens only for signed integers (int8, in16 and int32). I guess it's because of the way the conversion between integer types works. From go spec: "Conversions between integer types. If the value is a signed quantity, it is sign extended to implicit infinite precision ....". And there are several conversions to int64 and uint64 in the fmt package. This pathch solves only half of the problem. On a 32 bit system, an fmt.Printf("%b", int(-1)) should still print 64 ones.

R=golang-dev, r
CC=golang-dev
https://golang.org/cl/891049
parent 8a68b828
......@@ -162,6 +162,7 @@ var fmttests = []fmtTest{
fmtTest{"%x", b64, "ffffffffffffffff"},
fmtTest{"%b", 7, "111"},
fmtTest{"%b", b64, "1111111111111111111111111111111111111111111111111111111111111111"},
fmtTest{"%b", -6, "-110"},
fmtTest{"%e", float64(1), "1.000000e+00"},
fmtTest{"%e", float64(1234.5678e3), "1.234568e+06"},
fmtTest{"%e", float64(1234.5678e-8), "1.234568e-05"},
......
......@@ -306,14 +306,11 @@ func (f *fmt) fmt_uo32(v uint32) { f.integer(int64(v), 8, unsigned, ldigits) }
// fmt_uo formats a uint in octal.
func (f *fmt) fmt_uo(v uint) { f.integer(int64(v), 8, unsigned, ldigits) }
// fmt_b64 formats a uint64 in binary.
func (f *fmt) fmt_b64(v uint64) { f.integer(int64(v), 2, unsigned, ldigits) }
// fmt_b64 formats an int64 in binary.
func (f *fmt) fmt_b64(v int64) { f.integer(v, 2, signed, ldigits) }
// fmt_b32 formats a uint32 in binary.
func (f *fmt) fmt_b32(v uint32) { f.integer(int64(v), 2, unsigned, ldigits) }
// fmt_b formats a uint in binary.
func (f *fmt) fmt_b(v uint) { f.integer(int64(v), 2, unsigned, ldigits) }
// fmt_ub64 formats a uint64 in binary.
func (f *fmt) fmt_ub64(v uint64) { f.integer(int64(v), 2, unsigned, ldigits) }
// fmt_c formats a Unicode character.
func (f *fmt) fmt_c(v int) { f.padString(string(v)) }
......
......@@ -857,8 +857,12 @@ func (p *pp) doprintf(format string, a []interface{}) {
// int
case 'b':
if v, _, ok := getInt(field); ok {
p.fmt.fmt_b64(uint64(v)) // always unsigned
if v, signed, ok := getInt(field); ok {
if signed {
p.fmt.fmt_b64(v)
} else {
p.fmt.fmt_ub64(uint64(v))
}
} else if v, ok := getFloat32(field); ok {
p.fmt.fmt_fb32(v)
} else if v, ok := getFloat64(field); ok {
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment