Printing Binary in C#

I've been looking on and off for the last couple days for a way to easily convert binary data to a hex representation in C# for printing. As it turns out, the BitConverter class is normally used to do this:

string s = System.BitConverter.ToString(
    new byte[] { 1, 15, 17 }
);
// s contains: "01-0F-11"

It's also handy for packing and unpacking binary data:

// Given an integer, the converter always returns a 4-byte 
// array. The length of this array will depend on the data 
// type it's given.
byte[] bytes = System.BitConverter.GetBytes(42);
// bytes contains: { 42, 0, 0, 0 }

// ToInt32 always reads 4 bytes
int num = System.BitConverter.ToInt32(bytes, 0);
// num is: 42

Posted on June 4, 2009 from Calgary

Newest Articles

About

My name is Brandur. I'm a polyglot software engineer and part-time designer working at Heroku in San Francisco, California. I'm a Canadian expat. My name is Icelandic. Drop me a line at brandur@mutelight.org.

Aside from technology, I'm interested in energy and how it relates to our society, travel, longboarding, muay thai, symphonic metal, and the guitar.

If you liked this article, consider finding me on Twitter.