Learn to Read Binary and Hex Values

When you see the following numeric characters written down what do you think?

1234

One thousand two hundred and thirty-four. Right?

Probably, yes, the context is likely to be base-10, but what if it was hex?

0x1234

What is that value? In decimal it’s 4660.

The first four years of my career involved a lot of interaction with individual bits and bytes, which were being transmitted over serial port protocols. (one such example was. Modbus).

It was fun. It felt like proper programming.

Over the next decade, hardly anything at all like this came my way. And in those years, without realising, I’d lost a skill – The feeling for binary and hexadecimal numbers and how they translated to the comfortable decimal numbers with which we are all so familiar.

So, recently I was thrown into a project which involved translating the bytes coming from a serial port to a series of fields in a class. It wasn’t too taxing, but it was hindered by the fact that I had think about the conversions. It made me realise that this stuff can actually be quite useful.

Like a linguistic skill, it’s often better to learn to think in terms of the domain in which you are conversing. The best linguists, when communicating in German will think in German, rather than translating from their native language.

But my experience is that we often need to translate between these domains. Simply thinking in of that domain isn’t enough.

I’m not saying that you should be able to look at a hex value 2f5a109888aedfbc1, or a binary value of 00101010110100101010101010 and know instantly what decimal value it is. I’m suggesting that up to a sensible exponent of 2, you should have a feeling for the equivalent decimal and hex representation (the binary one follows directly from the exponent).

2^ Binary Hex Decimal
1 10 2 2
5 10000 10 16
8 100000000 100 256
10 10000000000 400 1024

I’m suggesting that a feel for this up to an exponent of 32 is desirable. This, of course, takes us to the limit of a 32-bit value – 4 bytes – or an int (probably) to you and I. An exponent of 31 (with one subtracted from the final number) gives us the boundary of an unsigned int, 16 gives us an unsigned short int, 15 a signed short int, etc.

An old professor of mine at university used to boast that he knew, by heart, the decimal representation  of each power of 2 up to an exponent of 64. This was met with moderate derision from some of his students, but maybe he had a point…

 

Leave a Reply