Bitwise Operations Part 1: A Quick Introduction to Bases
In this series, I will touch on the fundamentals of understanding binary and learning to reason with it, then how we can use it in Javascript.
What is decimal notation, really? #
We learn to count in decimals, or base 10. What this means is that each significant digits are counted in powers of 10. There is an infinite amount of base systems we can use, not just our familiar base 10. If we evaluate the same number in two different base systems, it would produce two completely different value. Let’s study the number 123. First in base 10, we would evaluate it like so:
12310 = 1*102 + 2*101 + 3*100 = 100 + 20 + 3
Now, let’s look at what 123 might look like in base 5.
1235 = 1*52 + 2*51 + 3*50 = 25 + 10 + 3 = 3810
So if we convert 123 from base 5 to base 10, it’s value would be 38. Instead of multiplying each digit in powers of 10, we evaluated it in powers of 5. Additionally, the value 5 in base 5 would be represented as 105, or 1*51 + 0*50 . Effectively, you would never write the digit 5 in base 5.
What, then, is binary notation? #
Simply put, binary counts in base 2, or powers of 2. From what we just learned, we can reason why you see binary as just 1’s and 0’s. Though the digit 2 does not exist in this base system, the value 2 is represented as 10, or 1*21 + 0*20 . We can then go on to reason that the value 123 might look something like this in binary:
12310 = 1*26 + 1*25 + 1*24 + 1*23 + 0*22 + 1*21 + 1*20 = 1111011
Here is a what it looks like to count to 10 in binary.
110 = 1
210 = 10
310 = 11
410 = 100
510 = 101
610 = 110
710 = 111
810 = 1000
910 = 1001
1010 = 1010
It should be noted that there is a completely different way to represent negative binary without the subtraction sign, but we don’t have to worry about that just yet.
As software engineers, one motivation for learning binary is to use bitwise operators to increase the efficiency of our programs. It’s not as important to be fluent at counting in binary as it is to understand the patterns associated with binary systems. Learning to reason in binary is the first step to understanding the flip-flops and logic gates that makes up our digital world. Continue onto part 2, Two’s Complement