In code, you’ll often see number values written out something like this:
or maybe even this …
In both cases, they’re describing the number we commonly
refer to as two hundred and fifty. So why don’t programmers just write “250”?
Well, the answer lies deep within the nature of digital electronics.
But first, it helps to get an objective idea of how the system we already know works.
Decimal is a base-10 numeral system. That means it uses 10 different character
symbols to represent numeric values - 0, 1, 2, 3, 4, 5, 6, 7, 8, & 9
A single Decimal digit can represent a maximum value of nine,
one more than that and we have to add another digit to the left
of the original
Decimal is a fine system, quite popular ;) - why - there it is on the top of my computer
keyboard
But - the computer itself doesn’t “think” in Decimal.
It stores values as electrical charges that can be measured as either Low or High,
Off or On …
… zero or one.
This system is known as “Binary”, and in binary, each digit is known as a bit.
A bit can hold a maximum value of 1, in order to represent more than 1 we need
to add another bit. So a 2 in binary looks like this …
and a three in binary looks like this …
As we keep counting up to ten, you’ll notice that binary uses up a lot
more space compared to good old decimal notation.
And that’s just a 4-bit value, most computers nowadays work with binary values
of 32-bit length …
Some even use 64-bit values …
At this point, even if we displayed these values in decimal notation,
they’re just ridiculously long and unwieldy.
So when writing code, It’s helpful to have a more convenient way
to represent them. And that’s where “Hexadecimal” notation
comes in handy.
Hexadecimal, or simply “hex” as it’s known to friends,
uses 16 characters to represent a number value. Like decimal, it uses the classics - 0,1,2,3,4,5,6,7,8,9
But It also uses letters, to represent values 10 through 15
like so …
Because of those extra characters, hexadecimal notation takes up less space in
text Making it easier for us humans to type out
or even simply remember a specific value.
Oh but wait - that’s not all! Hex also syncs up nicely with the way we group
Binary bits.
In Binary - a group of four bits is called a “nibble”
and a nibble can conveniently be represented by a single character in hexadecimal.
Because they’re both capable of storing the same maximum value -
fifteen
And 8 bits in Binary, which is called a byte, can be represented using only 2 hex characters.
In order to clearly specify when we’re using hexadecimal in code
we add a “0x” at the beginning of the value.
But in the end - no matter what system we use to represent a value in code
it’ll always be converted to binary & use the same amount of space within digital memory.
So regardless of what we see on the screen, underneath it all - its bits all the way down.