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
strconv.FormatUint if you want the string, but same idea.strconv.FormatUint for printing binary?fmt.Printf, I was hoping it was a replacement for the for-loop:-)fmt standard package altogether, and just use the built-in print command for this purpose. It's a low-level character output default mechanism, which is quite low-level and has zero calling overhead.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
strings.Trim() was an optional extra.fmt library — which already has highly optimised code to deal with these cases — will be an utter waste of time, memory and CPU. At the very last, if you're doing a function that emits a character a time, forget fmt.Printf(...) and just use the built-in, low-level print, which is a built-in Go command, designed for low-level character printing without any extra bells & whistles.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 standard package altogether, and just use the built-in print command for this purpose. It's a low-level character output default mechanism, which is quite low-level and has zero calling overhead.