12

How to print a byte array []byte{255, 253} as binary in Golang?

I.e.

[]byte{255, 253} --> 1111111111111101
Pylinux
  • 11,278
  • 4
  • 60
  • 67
  • By the way, that's a slice, not an array. In Go an array is an actual datatype different from slice and not just some vague list-like thing: https://stackoverflow.com/a/11737218/242457 – David Jones Mar 27 '23 at 15:55

3 Answers3

21

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

Becir
  • 3
  • 2
Pylinux
  • 11,278
  • 4
  • 60
  • 67
1

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
1

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
David Jones
  • 4,766
  • 3
  • 32
  • 45
  • 1
    This was a really good solution, thanks for adding it! I selected it as the accepted answer. BTW; do the answer need the strings.Trim() part? I feel the answer would be more concise without it – Pylinux Mar 28 '23 at 10:44
  • well, i tried to make it clear that the `strings.Trim()` was an optional extra. – David Jones Mar 28 '23 at 12:57
  • Don't mind me; it's still an excelent answer:-) – Pylinux Mar 29 '23 at 18:05