Skip to content

Commit d6311ff

Browse files
committed
math/big: add %#b and %O integer formats
Matching fmt, %#b now prints an 0b prefix, and %O prints octal with an 0o prefix. See golang.org/design/19308-number-literals for background. For #19308. For #12711. Change-Id: I139c5a9a1dfae15415621601edfa13c6a5f19cfc Reviewed-on: https://go-review.googlesource.com/c/160250 Reviewed-by: Rob Pike <[email protected]> Reviewed-by: Robert Griesemer <[email protected]>
1 parent 675503c commit d6311ff

File tree

2 files changed

+14
-4
lines changed

2 files changed

+14
-4
lines changed

src/math/big/intconv.go

+9-3
Original file line numberDiff line numberDiff line change
@@ -50,8 +50,9 @@ func writeMultiple(s fmt.State, text string, count int) {
5050
var _ fmt.Formatter = intOne // *Int must implement fmt.Formatter
5151

5252
// Format implements fmt.Formatter. It accepts the formats
53-
// 'b' (binary), 'o' (octal), 'd' (decimal), 'x' (lowercase
54-
// hexadecimal), and 'X' (uppercase hexadecimal).
53+
// 'b' (binary), 'o' (octal with 0 prefix), 'O' (octal with 0o prefix),
54+
// 'd' (decimal), 'x' (lowercase hexadecimal), and
55+
// 'X' (uppercase hexadecimal).
5556
// Also supported are the full suite of package fmt's format
5657
// flags for integral types, including '+' and ' ' for sign
5758
// control, '#' for leading zero in octal and for hexadecimal,
@@ -66,7 +67,7 @@ func (x *Int) Format(s fmt.State, ch rune) {
6667
switch ch {
6768
case 'b':
6869
base = 2
69-
case 'o':
70+
case 'o', 'O':
7071
base = 8
7172
case 'd', 's', 'v':
7273
base = 10
@@ -98,6 +99,8 @@ func (x *Int) Format(s fmt.State, ch rune) {
9899
prefix := ""
99100
if s.Flag('#') {
100101
switch ch {
102+
case 'b': // binary
103+
prefix = "0b"
101104
case 'o': // octal
102105
prefix = "0"
103106
case 'x': // hexadecimal
@@ -106,6 +109,9 @@ func (x *Int) Format(s fmt.State, ch rune) {
106109
prefix = "0X"
107110
}
108111
}
112+
if ch == 'O' {
113+
prefix = "0o"
114+
}
109115

110116
digits := x.abs.utoa(base)
111117
if ch == 'X' {

src/math/big/intconv_test.go

+5-1
Original file line numberDiff line numberDiff line change
@@ -214,8 +214,12 @@ var formatTests = []struct {
214214
{"10", "%y", "%!y(big.Int=10)"},
215215
{"-10", "%y", "%!y(big.Int=-10)"},
216216

217-
{"10", "%#b", "1010"},
217+
{"10", "%#b", "0b1010"},
218218
{"10", "%#o", "012"},
219+
{"10", "%O", "0o12"},
220+
{"-10", "%#b", "-0b1010"},
221+
{"-10", "%#o", "-012"},
222+
{"-10", "%O", "-0o12"},
219223
{"10", "%#d", "10"},
220224
{"10", "%#v", "10"},
221225
{"10", "%#x", "0xa"},

0 commit comments

Comments
 (0)