Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print a byte array as binary in golang?

Tags:

arrays

binary

go

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

I.e.

[]byte{255, 253} --> 1111111111111101
like image 267
Pylinux Avatar asked Aug 03 '17 18:08

Pylinux


People also ask

What is a [] byte in Golang?

The byte type in Golang is an alias for the unsigned integer 8 type ( uint8 ). The byte type is only used to semantically distinguish between an unsigned integer 8 and a byte. The range of a byte is 0 to 255 (same as uint8 ).

Is Bytearray a binary?

Byte arrays mostly contain binary data such as an image. If the byte array that you are trying to convert to String contains binary data, then none of the text encodings (UTF_8 etc.) will work.

How do I print a Bytearray?

You can simply iterate the byte array and print the byte using System. out. println() method.

What is Golang binary?

Go Binaries is an open-source server allowing non-Go users to quickly install tools written in Golang, without installing the Go compiler or a package manager — all you need is curl . Let's take a look at how it works, and how to use it!


1 Answers

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://play.golang.org/p/eVez0vD4pJk

like image 147
Pylinux Avatar answered Sep 24 '22 20:09

Pylinux