How to print a byte array as binary in golang?

Viewed 13913

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

I.e.

[]byte{255, 253} --> 1111111111111101
2 Answers

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
Related