In my previous post, I talked about working with binary and bitwise operators. I realized that for us to really understand how these operators work, we need to understand two things:
- base numbers
- how the operators work with these numbers under the hood
This post talks about base numbers, and how we come by them.
It is divided into bits (permit my pun), so the post will not be too long and boring.
Base numbers are numbers that are used to represent numeric values on the number system. They are basically numbers. Nothing more.
They just occur in other bases, the most popular being base10 or Decimal.
base 2 is Binary
base 8 is Octal
base 16 is HexaDecimal
The way to represent these bases is by saying n subscript base, e.g., 2 subscript 8 is 2 base 8. I cannot find a way to represent this in this post.
Base 10 numbers do not use these subscripts because we assume all numbers are in base 10 unless specified.
Numbers can occur in many bases, these are just the most common ones.
Base10 numbers are the traditional numbers we are used to: 1, 2, 3...9, 10.
Base numbers follow a pattern. Each base has a maximum representation of that base minus 1. For base 10, it is 9, 2 is 1 and 8 is 7. We are going to exemplify this with base10.
1, 2, ... 8, 9, 10, 11, 12, 13...98, 99, 100, 101 etc.
Notice that when the "numbers" get to 9, they went back to 1 and 0, same as when it got to 99, we added two zeros to the right side of 1. That is how tens, hundreds, thousands, etc. are represented - by the rightmost number.
This same pattern goes for other bases:
2 in base two is 10
8 in base eight is 10
16 in base 16 is 10 etc.
How this works is that the numbers start off as unit, then when you get to the maximum representation, you go to tens, and keep adding 1 till you get to the maximum number again.
That is why:
11 is 11 in base 10
3 is 11 in base 2
9 is 11 in base 8
17 is 11 in base 16.
We are going to learn more about base 2 and base 16 in the next lesson.
Conversion across Bases
First, we are going to talk about converting from other bases to base 10, then from 10 to other bases, and then across bases that are not 10.
Conversion from a base to base 10 is straightforward. You just raise each unit of the number to the power of its bases reducing it by index of each unit of the number.
For example, let's convert these numbers to base 10:
- 11 base 8
- 207 base 8
- 11 base 2
- 81 base 4
11 base 8 = 1*8^1 + 1*8^0 = 8 + 1 = 9 base 10
207 base 8 = 2*8^2 + 0*8^1 + 7*8^0 = 64 + 0 + 7 = 71
11 base 2 = 1*2^1 + 1*2^0 = 2 + 1 = 3
81 base 4 = 8*4^1 + 8*4^0 = 32 + 8 = 40
Please note that ^ represents power e.g. 2^2 is 2*2 = 4, 3^3 is 3*3*3 = 24
This post is, as a matter of fact, more about mathematics than coding, but trust me, you need it to advance in your career as a software developer.
Please stay tuned for the continuation. 😀
Top comments (0)