Printing a raw binary to stdout with Go

This is probably just me, but I found it surprisingly hard to output some raw binary data to stdout using Go (obviously it’s easy when tha knows how!). I [insert search engine here]ed it pretty hard, but couldn’t find any examples.

Using any of the methods from the fmt package resulted in a representation being printed, rather than the raw binary:

fmt.Println(gen.PseudoRandomData(16))

$go run src/print-binary1.go 
[19 234 189 238 126 50 65 77 46 130 105 26 50 12 217 195]

Then I looked at the binary package, but the only example was writing to a []byte buffer. Eventually, I found a breadcrumb in one of the mailing lists that led me to the solution:

binary.Write(os.Stdout, binary.LittleEndian, gen.PseudoRandomData(16))

One thought on “Printing a raw binary to stdout with Go

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s