Has anyone got an idea if there is any inbuilt functionality in Go for converting from any one of the numeric types to its binary number form.
For example, if 123
was the input, the string "1111011"
would be the output.
The strconv
package has FormatInt
, which accepts an int64
and lets you specify the base.
n := int64(123)
fmt.Println(strconv.FormatInt(n, 2)) // 1111011
DEMO: http://play.golang.org/p/leGVAELMhv
http://golang.org/pkg/strconv/#FormatInt
func FormatInt(i int64, base int) string
FormatInt returns the string representation of i in the given base, for 2 <= base <= 36. The result uses the lower-case letters 'a' to 'z' for digit values >= 10.
See also the fmt package:
n := int64(123)
fmt.Printf("%b", n) // 1111011
Building on the answer provided by @Mark
Although the OP asked how to print an integer, I often want to look at more then 64 bits worth of data, without my eyes boggling:
/* --- Credit to Dave C in the comments --- */
package main
import (
"bytes"
"fmt"
)
func main() {
fmt.Printf("<%s>
", fmtBits([]byte{0xDE, 0xAD, 0xBE, 0xEF, 0xF0, 0x0D, 0xDE, 0xAD, 0xBE, 0xEF, 0xF0, 0x0D}))
// OUTPUT:
// <11011110 10101101 10111110 11101111 11110000 00001101 11011110 10101101 10111110 11101111 11110000 00001101>
}
func fmtBits(data []byte) []byte {
var buf bytes.Buffer
for _, b := range data {
fmt.Fprintf(&buf, "%08b ", b)
}
buf.Truncate(buf.Len() - 1) // To remove extra space
return buf.Bytes()
}
see this code in play.golang.orgThis code works on big integers *big.Int
:
x := big.NewInt(123)
s := fmt.Sprintf("%b", x)
// s == "1111011"
because *big.Int
implements the fmt.Formatter
interface.
Taken from https://stackoverflow.com/a/23317788/871134
Unsafe pointers must be used to correctly represent negative numbers in binary format.
package main
import (
"fmt"
"strconv"
"unsafe"
)
func bInt(n int64) string {
return strconv.FormatUint(*(*uint64)(unsafe.Pointer(&n)), 2)
}
func main() {
fmt.Println(bInt(-1))
}