It's common knowledge that nearly all modern computers operate with binary,
but the reasons for that aren't as clear without looking at the fundamental
electrical components of a computer. Computers are machines of logic, where
everything is always in one of two states:
. It's a pretty
simple leap to say that we can represent
with the binary
- they're both binary systems, just using different
symbols for each 'column'.
The base electrical component used to build the logic circuits of a computer
is the transistor, which is essentially an on/off switch that can be
controlled electronically (similar to a relay).
is of course
another binary system, so the physical state of an electrical circuit- that is,
a switch being
is conducting electricity and a switch being
conducting- can be used to represent things like
When transistors connected together and arranged in particular ways, we can form logic gates, leading to basic logic blocks that can store information, do math, and eventually guide a ship to the moon.
Even though computers operate with individual
's (bits), it's not
efficient for human designers or operators to work at this level. Instead, the
smallest useable piece of information we can usually read or write to on a
computer is larger- typically a block of 8 bits (an octet) at the smallest.
With modern computers, a block of 8 bits is referred to as a byte.
We saw in the previous block that it was really convenient to store information using number systems with a higher base than 10. We also observed that hexadecimal fits great with binary- as long as it's arranged in blocks of 4 digits. In computing, a block of 4 binary digits is commonly referred to as a nibble (...a small 'byte'). With each hexadecimal digit equal to a nibble (a series of 4 bits), we can write a single byte (the base unit of information on a computer, made up of 2 nibbles or 8 bits), using just two hexadecimal digits.
After you've read that last sentence 3 or 4 times and the meaning has become clear, hopefully you'll come to see why it's often convenient for programmers to write out values in hexadecimal in their code. It's especially useful when not referencing an actual number, but instead a series of bits. For example, when controlling a string of LEDs with an Arduino, you might have the following sequence:
On/off is just 1's and 0's to a computer, so the same thing written in binary would be:
Which is just a number. In base10 (decimal), that number is 22. The phrase "set the LED string to 22" has no physical meaning though, so you'll often find 'numbers' like this written out using either hex or binary literals:
1 2 3 4 5
led_string = b00010110 or led_string = 0x16
Note: A lot of languages don't have/allow binary literals, so it's much more common to see and use hexadecimal. As a rule of thumb, always use hex values in your code, and if you feel it's necessary, you can write the binary values in nearby comments.