As the old joke goes, “There are 10 types of people, those that understand how binary numbers work and those that don’t.” Let’s get you into the “understand” group.
Binary is the type of numbering system that is native to computers. It is base-2. Numbers that normal people work with are called decimal or base-10.
For normal base-10 numbers you use the digits 0 through 9 to describe a number. Here’s how you would count out 10 things:
1
2
3
4
5
6
7
8
9
And now you’ve run out out digits. So you put a “1” in the tens place and a “0” in the ones place to get:
10
To try counting the same quantity in binary you’re first realization should be that you only have two digits (base-2) to work with: 0 and 1. So the counting would look like this:
1
And now you’ve immediately run out of digits. So you put a “1” in the twos place and a “0” in the ones place and start counting again:
10
11
And you’ve run out of digits again. This happens a lot with binary, which is why it’s not a great numbering system for people. Just continue the pattern to keep counting:
100
101
110
111
1000
1001
1010
We’ll stop here since we have now counted up to “10” in decimal.
Another way you can parse this number is to think of how each position represents a component of the number.
With binary 1010 the components are as follows:
1 * 2^3 = 8
0 * 2^2 = 0
1 * 2^1 = 2
0 * 2^0 = 0
Adding 8 + 2 gets you to 10 decimal.
You’ve probably heard the term “8-bit” so what is an 8-bit number? Because bits are either 0 or 1 they are represented as binary. So an 8-bit binary number with all values set to one is this:
11111111
That is the largest number you can fit into 8 bits. And converted to decimal it is:
1 * 2^7 + 1 * 2^6 + 1 * 2^5 + 1 * 2^4 + 1 * 2^3 + 1 * 2^2 + 1 * 2^1 + 1 * 2^0
That breaks down to:
128 + 64 + 32 + 16 + 8 + 4 + 2 + 1
Which sums to 255, a number I’m sure you’ve seen around before. It is the maximum value you get with the UInt8 data type in Xojo.
Conversely, you can convert a decimal number to binary by repeatedly dividing it by 2 and noting the remainder. When the remainder is even you write a 0, when it is odd you write a 1. And then you read the number from the bottom up.
So to convert decimal 10 to binary:
10 / 2 = 5, with a remainder of 0. 0 is even so write a “0”:
0
Now divide 5 / 2 to get 2 with a remainder of 1, which is odd:
0
1
Now divide 2 /2 to get 1, with a remainder of 0:
0
1
0
Lastly, divide 1 / 2 to get 0 with a remainder of 1 which is odd. So you end up with this:
0
1
0
1
Reading that from the bottom up gives you: 1010
I hope you now consider yourself part of the group that understands binary!
This post originally appeared on the Xojo blog.
Top comments (0)