Skip to content

Decimal, Binary, and Hex

Glenn Salaman edited this page Sep 7, 2020 · 2 revisions

In this section, we're going to talk about bases.

Decimal, or base 10

To figure out the value of a base 10 number, we have to multiply each digit by it's digit "value". The first digit gets multiplied by 10^0, the second 10^1, the third 10^2, and so on. Here's an example:

Consider the number 287. We get the math value 287 by doing the following:

(2 * 10^2) + 8 * 10^1) + (7 * 10^0)  
10^2 is 100, 10^1 is 10, and 10^0 is one...so our resultant value simplifies to:  
2 * 100 + 8 * 10 + 7 * 1    or 287.

Binary, or base 2

We can do that same thing with binary...except that we use 2 instead of 10 when raising digits to a given power. Lets start by looking at a 4 bit number:

0b1010

The 0b on the front of the number is an indicator that 1010 is in bits...and doesn't mean "one-thousand ten".
So, to convert this to decimal:

1 * 2^3 + 0 * 2^2 + 1 * 2^1 + 0*2^0  
1 * 8   + 0 * 4   + 1 * 2   + 0*1  
  8     +   0     +   2     +  0
or 10.

Hexidecimal (hex for short), or base 16

Hex numbers use the 0x prefix to show that they're base 16. Note that if we want a hex digit, we can reuse 0-9, but when we get to 10 through 15, we need a different character...so we use a through f. So, here's a quick mapping for hex digits:

0x0 = 0
0x1 = 1
0x2 = 2
...
0x9 = 0
0xa = 10
0xb = 11
0xc = 12
0xd = 13
0xe = 14
0xf = 15

Here's a 2 digit hex number example:

0x3c
3 * 16^1 + 12 * 16^0
3 * 16   + 12
48       + 12
60

Note that a 2 digit hex number represents 8 bits or 1 byte...a very common computer unit. Which leads to:

Converting binary to hex...the embedded programmer's shorthand

Each hex digit represents 4 bits of info. Said another way, each hex digit represents a 4 digit binary number. We call these 4 bit chunks "nibbles". Here's a table for those translations, including the decimal values

Hex Binary Decimal
0 0000 0
1 0001 1
2 0010 2
3 0011 3
4 0100 4
5 0101 5
6 0110 6
7 0111 7
8 1000 8
9 1001 9
a 1010 10
b 1011 11
c 1100 12
d 1101 13
e 1110 14
f 1111 15

So now here's the shorthand...you can use this table to convert each hex digit to 4 binary bits. For example, our previous number 0x3c can be converted to:

3 -> 0011
c -> 1100

So 3c -> 00111100

You can go the other way too:

0b11111001 
1111 -> f
1001 -> 9

so 0b11111001 -> 0xf9