How to print a byte array []byte{255, 253}
as binary in Golang?
I.e.
[]byte{255, 253} --> 1111111111111101
How to print a byte array []byte{255, 253}
as binary in Golang?
I.e.
[]byte{255, 253} --> 1111111111111101
Simplest way I have found:
package main
import "fmt"
func main() {
bs := []byte{0x00, 0xfd}
for _, n := range(bs) {
fmt.Printf("%08b ", n) // prints 00000000 11111101
}
}
Playground with this code: https://go.dev/play/p/piJV_3OTHae
Or use this simple version
func printAsBinary(bytes []byte) {
for i := 0; i < len(bytes); i++ {
for j := 0; j < 8; j++ {
zeroOrOne := bytes[i] >> (7 - j) & 1
fmt.Printf("%c", '0'+zeroOrOne)
}
fmt.Print(" ")
}
fmt.Println()
}
[]byte{0, 1, 127, 255} --> 00000000 00000001 01111111 11111111
fmt.Printf
can print slices and arrays and applies the format to the elements of the array. This avoids the loop and gets us remarkably close:
package main
import "fmt"
func main() {
bs := []byte{0xff, 0xfd}
fmt.Printf("%08b\n", bs) // prints [11111111 11111101]
}
Playground with above code: https://go.dev/play/p/8RjBJFFI4vf
The extra brackets (which are part of the slice notation) can be removed with a strings.Trim()
:
fmt.Println(strings.Trim(fmt.Sprintf("%08b", bs), "[]")) // prints 11111111 11111101