Roger Ngo's Website

Personal thoughts about life and tech written down.

Easy Binary to Hexadecimal Conversion and Back

The following discussion is aimed to help us quickly convert binary-based numbers to hexadecimal-based and vice versa.

Just like how us humans represent our numbers in decimal (base-10), computers have their own systems. In base-10 decimal, we are allowed ten different digits to represent base values. 0-9. For base-2 binary, we're allowed two different digits: 0 and 1. As it turns out, binary is very convenient to represent states of OFF (0) and ON (1) for electronics. This little fact is what makes binary very useful and advantageous when dealing with signals digitally. That is as much as I can say as I do not have a thorough background in electrical engineering and signal processing. :)

In base-10, we have one's, ten's, hundred's places and so forth — we can represent a number by multiplying the current digit by 10 to the current place of the digit as its power.

For example, suppose we have the base-10 value of 932. In decimal, this number is represented as:

We begin the calculation for the powers at 0, and increment by 1 as we move up in the position of the number.

Binary is conceptually the same as decimal. For binary, we have the zero's, two's, four's, eight's, sixteen's, thirty-two's places, etc.

As you can see, we use the value 2 as a base for converting our binary values to decimal. Suppose we have the value 101011:

Hexadecimal is just the same as decimal, or binary. We use 16 different values to represent our numbers. The numbers are 0-9 and A-F. A, B, C, D, E, F in this case represent 10, 11, 12, 13, 14, 15 respectively. We can then equivalently say that hexadecimal is base-16.

Here's the number chart:

Similarly on how we were able to represent binary numbers in decimal, we can apply the same technique with representing hexadecimal in decimals. Take the number FA2C:

Converting from binary to hexadecimal is even easier. The trick here is to divide the binary digits into groups of 4 bits. Conveniently, groups of 4 bits in binary represent a maximum range of 16 values (0-15). The values go from 0000 to 1111. So from here, we would need to just map the corresponding values to the hexadecimal value.

For example:

To convert back to binary, we just do the reverse by decomposing each digit and individually converting them into binary:

Two hexadecimal digits usually represent an 8-bit byte. Therefore you will commonly come across notation such as 0x12 to represent the binary value 0001 0010. The prefix 0x tells us that the number is in hexadecimal notation. You will also see that some programmers use the $ notation too to represent hexadecimal when working machines such as SNES. For binary, the prefix will usually be 0b and for decimal, 0d.