15

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

I.e.

[]byte{255, 253} --> 1111111111111101
1
  • 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: stackoverflow.com/a/11737218/242457 Commented Mar 27, 2023 at 15:55

3 Answers 3

22

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

Sign up to request clarification or add additional context in comments.

4 Comments

There's also strconv.FormatUint if you want the string, but same idea.
@JimB Do you have a playground with an example of strconv.FormatUint for printing binary?
OK, so it's a replacement for the fmt.Printf, I was hoping it was a replacement for the for-loop:-)
Please consider skipping the 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.
7

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

4 Comments

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🤔
well, i tried to make it clear that the strings.Trim() was an optional extra.
Don't mind me; it's still an excelent answer:-)
Definitely the only solution to consider. Anything else that also uses the 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.
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 Comment

Please consider skipping the 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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.