All integers can be expressed in any number base. The key is to have defined symbols. Hexadecimal is a perfect example of adding in symbols to fill the base range.
Decimal base range
0, 1, 2, 3, 4, 5, 6, 7, 8, 9 # 10 in all
Binary base range
0, 1 # 2 in all
Hexadecimal base range
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F # 16 in all
Recall that in base 10, 99 can be written as,
9 * 10 + 9
The high order digit is one magnitude of 10, the low order digit is zero magnitude of 10.
9 * 10 ** 1 + 9 * 10 ** 0 == 99 base 10
Now what happens if we replace the 10
with 16
?
9 * 16 ** 1 + 9 * 16 ** 0 == 99 base 16 == 144 + 9 == 153
To convert the decimal value back into hex, we simply reverse the process…
153 / 16 == 10 ** 1 * 144 / 16 + 10 ** 0 * 9 == 90 + 9
Regardless what base we are working, there are repeating number patterns.
FFFF
can be written as
FF * 256 + FF
Notice that 256 is the square of 16. In other words, 2 magnitudes of 16.
3 2 1 0 => magnitude
F F F F
* 16 ** 3 16 ** 2 16 ** 1 16 ** 0
The above is the same as,
15 * 16 ** 3 + 15 * 16 ** 2 + 15 * 16 ** 1 + 15 * 16 ** 0
61440 + 3840 + 240 + 15 == 65535
Now let’s work it backwards.
>>> 65535 % 16
15 # F
>>> 65535 // 16
4095
>>> 4095 % 16
15 # F
>>> 4095 // 16
255
>>> 255 % 16
15 # F
>>> 255 // 16
15
>>> 15 % 16
15 # F
>>> 15 // 16
0
>>>
Notice that we assign the symbol to the modulo, not the quotient.floor.
Okay, so base 10 goes up by one placeholder for each magnitude, as does base 16, so it follows then that so will base 2.
2 ** [7 6 5 4 3 2 1 0]
1 1 1 1 1 1 1 1
Which in expanded form is,
1000 0000 +
100 0000 +
10 0000 +
1 0000 +
1000 +
100 +
10 +
1
Note that each group of four bits is in the range 0 though 15, (0 … F)
1111 => F => 15
2 ** 7 + 2 ** 6 + 2 ** 5 + 2 ** 4 + 2 ** 3 + 2 ** 2 + 2 ** 1 + 2 ** 0
128 + 64 + 32 + 16 + 8 + 4 + 2 + 1 => 255 => FF
Converting decimal to binary is a little more involved than converting hex to binary and vice versa. Each group of 4 represents one magnitude of 16.
15 == 16 ** 1 - 1
255 == 16 ** 2 - 1
4095 == 16 ** 3 - 1
65535 == 16 ** 4 - 1
1111 1111 1111 1111 == 65535
F F F F
>>> 15 % 2
1 # bit 4
>>> 15 // 2
7
>>> 7 % 2
1 # bit 3
>>> 7 // 2
3
>>> 3 % 2
1 # bit 2
>>> 3 // 2
1
>>> 1 % 2
1 # bit 1
>>> 1 // 2
0
>>>