aboutsummaryrefslogtreecommitdiff
path: root/src/math/big
diff options
context:
space:
mode:
authorRuss Cox <rsc@golang.org>2019-01-30 00:55:38 -0500
committerRuss Cox <rsc@golang.org>2019-02-26 19:39:19 +0000
commitd6311ff1e43dd1e7c9cb9edccd10a04b63a7c41f (patch)
treefff0d7791115991eba2ac4da9b98dd58d3a30733 /src/math/big
parent675503c507194a48c01a39a0f25a6d0c9d772477 (diff)
downloadgo-d6311ff1e43dd1e7c9cb9edccd10a04b63a7c41f.tar.xz
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 <r@golang.org> Reviewed-by: Robert Griesemer <gri@golang.org>
Diffstat (limited to 'src/math/big')
-rw-r--r--src/math/big/intconv.go12
-rw-r--r--src/math/big/intconv_test.go6
2 files changed, 14 insertions, 4 deletions
diff --git a/src/math/big/intconv.go b/src/math/big/intconv.go
index 6cca827c8e..65174c5018 100644
--- a/src/math/big/intconv.go
+++ b/src/math/big/intconv.go
@@ -50,8 +50,9 @@ func writeMultiple(s fmt.State, text string, count int) {
var _ fmt.Formatter = intOne // *Int must implement fmt.Formatter
// Format implements fmt.Formatter. It accepts the formats
-// 'b' (binary), 'o' (octal), 'd' (decimal), 'x' (lowercase
-// hexadecimal), and 'X' (uppercase hexadecimal).
+// 'b' (binary), 'o' (octal with 0 prefix), 'O' (octal with 0o prefix),
+// 'd' (decimal), 'x' (lowercase hexadecimal), and
+// 'X' (uppercase hexadecimal).
// Also supported are the full suite of package fmt's format
// flags for integral types, including '+' and ' ' for sign
// control, '#' for leading zero in octal and for hexadecimal,
@@ -66,7 +67,7 @@ func (x *Int) Format(s fmt.State, ch rune) {
switch ch {
case 'b':
base = 2
- case 'o':
+ case 'o', 'O':
base = 8
case 'd', 's', 'v':
base = 10
@@ -98,6 +99,8 @@ func (x *Int) Format(s fmt.State, ch rune) {
prefix := ""
if s.Flag('#') {
switch ch {
+ case 'b': // binary
+ prefix = "0b"
case 'o': // octal
prefix = "0"
case 'x': // hexadecimal
@@ -106,6 +109,9 @@ func (x *Int) Format(s fmt.State, ch rune) {
prefix = "0X"
}
}
+ if ch == 'O' {
+ prefix = "0o"
+ }
digits := x.abs.utoa(base)
if ch == 'X' {
diff --git a/src/math/big/intconv_test.go b/src/math/big/intconv_test.go
index 2e01ee327d..d23a3e2beb 100644
--- a/src/math/big/intconv_test.go
+++ b/src/math/big/intconv_test.go
@@ -214,8 +214,12 @@ var formatTests = []struct {
{"10", "%y", "%!y(big.Int=10)"},
{"-10", "%y", "%!y(big.Int=-10)"},
- {"10", "%#b", "1010"},
+ {"10", "%#b", "0b1010"},
{"10", "%#o", "012"},
+ {"10", "%O", "0o12"},
+ {"-10", "%#b", "-0b1010"},
+ {"-10", "%#o", "-012"},
+ {"-10", "%O", "-0o12"},
{"10", "%#d", "10"},
{"10", "%#v", "10"},
{"10", "%#x", "0xa"},