Hex and ASCII

Let’s learn about the hexadecimal number system and American Standard Code for Information Interchange (ASCII).

Hex

The main reason we need hex is that it provides a compact way of representing binary numbers. This is particularly helpful for cryptographic keys, which are often very long when represented in binary.

Writing a number in hex

We use the base number 16 instead of 10 in decimal (and 2 in binary) for hex numbers. Thus:

  1. The digits of a hex number can, in theory, take any of the values between 0 and 15.

  2. Every digit in a hex number will be multiplied by some power of 16. The powers of 16 start with 0 (the furthest digit to the right) and then increase from right to left.

The first requirement causes a slight problem since it will be hard to determine whether 12 means the digit 1 followed by the digit 2, or whether we mean the hex ‘digit’ 12. Thus, we replace the hex digits 10, 11, 12, 13, 14, and 15 with A, B, C, D, E, and F, respectively. So, in practice, the digits of a hex number take any of the values between 0 and 9 and between A and F.

Converting hex to decimal

Converting hex to decimal follows the same principles as binary to decimal, except now we are using multiples and powers of 16. Consider the hex number B5F16B5F_{16}. It follows that:

B5F16=(B×162)+(5×161)+(F×160)B5F_{16} = (B \times 16^2 ) + (5 \times 16^1 )+(F \times 16^0)

=(11×162)+(5×161)+(15×160)= (11 \times 16^2 ) + (5 \times 16^1 ) + (15 \times 16^0)

=(11×256)+(5×16)+(15×1)=2816+80+15= (11 \times 256) + (5 \times 16) + (15 \times 1) = 2816 + 80 + 15

=291110= 2911_{10}

Thus, B5F in hex is 2911 in decimal.

Here, we have a coded example of the hex to decimal conversion defined above:

Get hands-on with 1200+ tech skills courses.