Number systems — theory with the colours of a photo: binary, octal, hexadecimal and base conversion step by step (and the sunset that came out navy blue)
For a class presentation I wanted to use, as a background, the colour of the sky in a sunset photo I took at Las Canteras beach. I opened the photo in my phone’s editor, tapped the sky with the eyedropper and got three numbers: red 244, green 162 and blue 97. The slide software had a box that said «Colour: #», and I calmly typed #244162. The slide turned an almost black navy blue. What had happened? The box expected hexadecimal and I had given it decimal. Same digits, another base, another colour. That day I understood that a number without its base is not a number: it is a riddle.
This is the second paper topic of Computer Engineering I (IC1). In the previous one, introduction to computers, we saw that inside the machine everything is bits. Today we learn to read and write them: what a positional number system is, how decimal, binary, octal and hexadecimal work, how you count in each one and, above all, how to convert a number from one base to another, fractional part included. Everything revolves around the colour of that photo, #F4A261, because colours are where you see the most hexadecimal without noticing. Afterwards, in the number systems practice we solve the typical exam problems step by step, and in the exercises it is your turn.
Table of Contents
Before you start. For this topic you only need to know how to multiply, how to do a division with its quotient and remainder (162 divided by 2 is 81 with 0 left over) and what a power is: = 2 · 2 · 2 = 8, any number to the power of 0 is 1, and a negative exponent means dividing ( = 0.5). Nothing else. The topic goes in this order: first, how a number is built from its digits (the weights formula); then decimal and binary, and how to convert from one to the other in both directions, with the integer and fractional parts handled separately; next, octal and hexadecimal, which are binary written shorter; and finally, the map with every conversion and how many digits a number needs. If you get lost at any point, go back to the colour of the photo, #F4A261: the whole topic can be told with its three channels.
What a number system is
A number system is a set of symbols (the digits) and some rules to combine them and represent quantities. All the ones we are going to see have two things in common:
- They have a base B, which is the number of different digits: from 0 to . Decimal has ten (base 10), binary two (base 2), octal eight (base 8) and hexadecimal sixteen (base 16).
- They are positional: the same digit is worth something different depending on the position it occupies.
You use positional notation every day without thinking. Look at the 3 in these three numbers: 3, 30 and 300.
The digit is the same; what changes is its weight. Each position has a weight that is a power of the base, and the value of the number is the sum of each digit multiplied by its weight. In general, for a number with m digits in the integer part and n in the fractional part:
where is the digit in position i, B is the base and is the weight of that position. Position 0 is the units, just to the left of the point; to the left the weights go up (…) and to the right they go down (…).
This formula is the whole topic. Converting «from any base to decimal» is applying it as it is; converting «from decimal to any base» is doing it backwards. Everything else is shortcuts.
The formula in words
Before using it, read it out loud: each digit is worth what it says multiplied by what its slot is worth, and the number is the sum of everything. What each slot is worth, its weight, depends on only two things: the base and how far the slot is from the point.
With a number you already know, the 244 of the red channel, read in base 10:
| Position | Digit | Weight | Adds | Why |
|---|---|---|---|---|
| 2 | 2 | 100 () | 200 | It is two slots to the left of the units: multiplied by the base twice |
| 1 | 4 | 10 () | 40 | One slot to the left: multiplied by the base once |
| 0 | 4 | 1 () | 4 | It is the units slot, and = 1 in any base |
| 244 | The sum of what each digit adds |
Now keep the digits still and change only the base to 16. The weights become 256, 16 and 1, and the sum is 2 · 256 + 4 · 16 + 4 · 1 = 580. The same three digits, another number. That is, in small, what happened to me with the colour box.
To the right of the point the same thing happens, but dividing: the first slot weighs = 1/B, the second , and so on. In decimal they are tenths (0.1) and hundredths (0.01); in binary, halves (0.5) and quarters (0.25); in hexadecimal, the first slot after the point is already worth a sixteenth, 0.0625.
The decimal system
Decimal uses ten digits (0-9) and its weights are powers of 10. We know it so well we do not see the formula, but it is there. Take 4096.25:
| Digit | 4 | 0 | 9 | 6 | . | 2 | 5 |
|---|---|---|---|---|---|---|---|
| Weight |
The leftmost digit is the most significant digit (MSD, the one with the largest weight) and the rightmost one the least significant digit (LSD). In binary we will call them MSB and LSB (bit instead of digit).
Counting in decimal
With 1 digit you count from 0 to 9: 10 numbers. Going past 9, the digit goes back to 0 and you «carry one» to the next position: 10. With 2 digits you reach 99 ( numbers) and with 3, 999. In general:
Notice that «− 1»: with 3 digits there are 1000 numbers, but the largest is 999, because 0 also counts. It is the most forgotten rule, and it works the same in every base.
The binary system
Binary is the system computers use: it only has two digits, 0 and 1 (the bits), because they are the two logic levels we saw in the previous topic. It is positional and its base is 2, so the weights are powers of 2:
| Position | 7 | 6 | 5 | 4 | 3 | 2 | 1 | 0 | . | −1 | −2 | −3 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
| Weight | 128 | 64 | 32 | 16 | 8 | 4 | 2 | 1 | 0.5 | 0.25 | 0.125 |
Learn this row by heart (at least up to 1024 and down to 0.0625). There is no calculator in the exam, and almost every sum in this topic is adding or subtracting powers of 2.
Counting in binary and the ranges
Counting in binary is like an odometer whose wheels only have 0 and 1: 0, 1 and, going past it, back to 0 and carry one: 10, 11, 100, 101, 110, 111, 1000…
With m bits there are combinations, from 0 to . With 4 bits, from 0000 to 1111 (0 to 15); with 8 bits, from 0 to 255. That is why each channel of a colour goes from 0 to 255: each channel takes 8 bits. You will need this table for the whole topic:
| Decimal | Binary | Octal | Hex | Decimal | Binary | Octal | Hex |
|---|---|---|---|---|---|---|---|
| 0 | 0000 | 0 | 0 | 8 | 1000 | 10 | 8 |
| 1 | 0001 | 1 | 1 | 9 | 1001 | 11 | 9 |
| 2 | 0010 | 2 | 2 | 10 | 1010 | 12 | A |
| 3 | 0011 | 3 | 3 | 11 | 1011 | 13 | B |
| 4 | 0100 | 4 | 4 | 12 | 1100 | 14 | C |
| 5 | 0101 | 5 | 5 | 13 | 1101 | 15 | D |
| 6 | 0110 | 6 | 6 | 14 | 1110 | 16 | E |
| 7 | 0111 | 7 | 7 | 15 | 1111 | 17 | F |
To write 0 to 15 in binary without thinking, the rightmost column alternates 0, 1, 0, 1; the next one goes in twos (0, 0, 1, 1); the next one in fours, and the last one in eights.
Why combinations? Because every bit you add doubles the ones you had: you can write all the previous ones with a 0 in front and then all of them again with a 1 in front.
| Bits | Combinations | From 0 to | Why |
|---|---|---|---|
| 1 | 2 | 1 | Just 0 or 1 |
| 2 | 4 | 3 | The previous 2 with a 0 in front (00, 01) and with a 1 in front (10, 11) |
| 3 | 8 | 7 | Double again: 4 with a 0 in front and 4 with a 1 in front |
| 4 | 16 | 15 | The 16 rows of the table above |
| 8 | 256 | 255 | Doubling eight times: . It is one colour channel |
The largest number is always «all ones», and it is one less than the number of combinations: 1111 is 15, not 16, because if you add 1 every digit goes past its maximum, goes back to 0 and you carry one into a new slot: 10000, which is 16. It is the same «− 1» as the 999 in decimal.
From binary to decimal: the sum of weights
To convert a binary number to decimal you apply the formula from the start: each bit times its weight. Since bits are only 0 or 1, in practice it is even easier: add up the weights of the bits that are 1 and ignore the rest.
The red channel of the photo’s colour, in binary, is 11110100. And if we add two bits of fractional part, 11110100.11:
The integer part, 11110100, is 244: the red of the sky. The fractional part, .11, is 0.75. We will see later where that 0.75 comes from in the photo editor.
Write the weights above the bits before adding, starting with the 1 just to the left of the point. If you start counting from the left of the number, the first bit you skip shifts all the weights.
From decimal to binary
The other way round there are two methods, and it pays to know both: one to understand and one not to make mistakes.
Method 1: the sum of weights
Look for the largest power of 2 that does not exceed the number, subtract it and repeat with what is left, until you reach 0. Each power used is a 1; the rest, 0. With the red channel, 244:
| Left | Largest power that fits | Remainder |
|---|---|---|
| 244 | 128 () | 116 |
| 116 | 64 () | 52 |
| 52 | 32 () | 20 |
| 20 | 16 () | 4 |
| 4 | 4 () | 0 |
We used and : ones in positions 7, 6, 5, 4 and 2, and zeros in 3, 1 and 0. Result: 11110100. It is quick with small numbers, but with large ones it is easy to skip a power.
There is a detail that makes this method always work: you never need to use the same power twice. If in 244 you could use 64 twice, that would be 128, and you would have taken 128 before. And all the smaller powers together do not reach the next one: 1 + 2 + 4 + 8 + 16 + 32 + 64 = 127, exactly one less than 128. That is why each power is used once or not at all, that is, each position is a 1 or a 0, and every number has only one way of being written in binary.
Check you’ve got it: convert the blue of the colour, 97, to binary with the sum of weights, and check the result the other way round.
You get 1100001, which with the 8 bits of a channel is 01100001. Step by step: the largest power that fits in 97 is 64 (), leaving 33; 32 () fits in 33, leaving 1; 1 () fits in 1, leaving 0. Ones in positions 6, 5 and 0, and zeros in 4, 3, 2 and 1. The other way round, with the sum of weights: 64 + 32 + 1 = 97. The leading 0 does not change the value; it is written because a channel always takes 8 bits, and it is exactly what the {n:08b} in the program further down does.
Method 2: successive divisions
It is more mechanical: divide by 2, write down the remainder and divide the quotient again, until you cannot go on. The last quotient is the most significant bit, followed by the remainders read from bottom to top. With the green channel, 162:
Why are they read backwards? Because the first remainder tells you whether the number is even or odd: it is the units bit, the one with weight 1 (LSB). Each division «shifts» the number one bit to the right, so each new remainder is a bit with more weight than the previous one. The last to come out is the most significant.
To see it with your own eyes, cheat for a moment and write next to each number what it looks like in binary. In the exam you do not have that column (it is exactly what you are looking for); here it is only to see why the method works:
| Number | In binary | Divided by 2 | Remainder | Why |
|---|---|---|---|---|
| 162 | 10100010 | 81 | 0 | 162 is even: its units bit is 0 |
| 81 | 1010001 | 40 | 1 | 81 is 162 without its last bit, and it is odd: the next bit is 1 |
| 40 | 101000 | 20 | 0 | Again the last bit is removed and the remainder is that bit |
| 20 | 10100 | 10 | 0 | Same |
| 10 | 1010 | 5 | 0 | Same |
| 5 | 101 | 2 | 1 | Odd: the bit that goes is a 1 |
| 2 | 10 | 1 | 0 | Same |
| 1 | 1 | It cannot be divided any more: this last quotient is the most significant bit |
Look at the «In binary» column: each row is the one above without its last digit. Dividing by 2 is deleting the units bit, and the remainder is exactly the bit that gets deleted. That is why the bits come out from right to left. In decimal the same thing happens with 10: 4096 divided by 10 is 409 with 6 left over, and 6 is the last digit of 4096.
Writing the remainders in the order they come out. 162 would become 01000101, which is 69. If you checked with the sum of weights (128 + 32 + 2 = 162) you would see it straight away.
The fractional part: successive multiplications
Divisions only work for the integer part. For the fractional part you do the opposite: multiply by 2, the integer part of the result (0 or 1) is the next digit, and you keep multiplying only what is left after the point. The digits are read from top to bottom, in the order they come out.
In the photo editor, the title text sits on a layer with an opacity of 0.75 (75 %). In binary:
| I multiply | Result | Digit | Carry on with |
|---|---|---|---|
| 0.75 × 2 | 1.5 | 1 | 0.5 |
| 0.5 × 2 | 1.0 | 1 | 0 (end) |
Exact: 0.5 + 0.25 = 0.75. But now try an opacity of 0.4:
After four multiplications 0.4 comes back, so the digits 0110 repeat forever: 0.4 in binary is 0.0110 0110 0110… If we only keep 4 digits, we are storing 0.0110, which is 0.25 + 0.125 = 0.375. The difference, , is the representation error.
And why does multiplying by 2 bring out the digits of the fractional part? Because multiplying by the base moves the point one slot to the right. In decimal you do it without thinking: 0.25 · 10 = 2.5, and the first digit after the point, the 2, has crossed over to the integer side. In binary, with 0.75 = 0.11: multiplying by 2 gives 1.1, and the 1 that has crossed the point is the first digit. What is left after the point, 0.1, is multiplied again: 1.0, and that 1 is the second digit. Since each multiplication brings out the digit that was closest to the point, they are read from top to bottom, the opposite of the remainders.
The table for 0.4, with the reason for each row:
| I multiply | Result | Digit | Carry on with | Why |
|---|---|---|---|---|
| 0.4 × 2 | 0.8 | 0 | 0.8 | 0.4 does not reach a half: the 0.5 slot is not used |
| 0.8 × 2 | 1.6 | 1 | 0.6 | 0.8 does go past a half: the 0.25 slot is used |
| 0.6 × 2 | 1.2 | 1 | 0.2 | It goes past again: the 0.125 slot is used |
| 0.2 × 2 | 0.4 | 0 | 0.4 | It does not reach it: the 0.0625 slot is not used |
| 0.4 × 2 | … | 0.4 already came out in the first row: from here on everything repeats |
That is how you know a number is periodic without doing infinitely many sums: as soon as what you «carry on with» repeats a value you already had, the digits that follow are the same ones that already came out.
Check you’ve got it: how do you write 0.625 in binary, the other «exact» fraction in the note below?
0.101. Step by step: 0.625 · 2 = 1.25, digit 1 and carry on with 0.25; 0.25 · 2 = 0.5, digit 0 and carry on with 0.5; 0.5 · 2 = 1.0, digit 1 and 0 is left, so it ends. The digits are read from top to bottom: 0.101. Check it with the weights: 0.5 + 0.125 = 0.625. It ends because 0.625 is a sum of halves and eighths.
A decimal number with a fractional part is only exact in binary if its fractional part is a sum of halves, quarters, eighths… (0.5, 0.75, 0.625, 0.8125). Numbers as innocent as 0.1, 0.3 or 0.4 are periodic in binary. That is why in almost any language 0.1 + 0.2 is not exactly 0.3. We will see it in depth in the floating-point topic.
A number with integer and fractional parts
You do both separately and join them with the point: divisions for the integer part, multiplications for the fractional part. For example, 244.75 = 11110100 (divisions of 244) + .11 (multiplications of 0.75) = 11110100.11, which is exactly the number in the weights drawing. The circle is closed.
Always state the base
Go back to the story at the start. The number «244» can be:
- : two hundred and forty-four.
- : .
- : .
And «10» is ten, two, eight or sixteen depending on the base. That is why, when several bases are involved, the base is written as a subscript after the number: , whereas is one thousand one hundred and ten. In programming you will also see prefixes: 0b11110100 (binary), 0o364 (octal) and 0xF4 (hexadecimal); and in colours, the hash sign: #F4A261.
What the colour box read
Now you can fully explain what happened to the slide. The «Colour: #» box expects exactly 6 hexadecimal digits, two per channel, and it cuts them like this, without asking: the first two are red, the next two green and the last two blue. I typed 244162, thinking of «244» and «162», but it read 24 | 41 | 62. The blue, 97, did not even fit.
| Channel | Digits it read | Value it took | What I wanted | Why |
|---|---|---|---|---|
| Red | 24 | 2 · 16 + 4 = 36 | F4 = 244 | It read my digits as hexadecimal and cut them in a different place |
| Green | 41 | 4 · 16 + 1 = 65 | A2 = 162 | The 4 at the end of the red and the 1 of the green ended up together |
| Blue | 62 | 6 · 16 + 2 = 98 | 61 = 97 | It took the «62» of the green; my 97 never got in |
The colour that came out was red 36, green 65 and blue 98: all three channels below 128, that is, below 80 in hexadecimal, and blue the highest of the three. A dark blue, almost black: the navy blue of the slide. What I should have typed was each channel converted to hexadecimal, F4, A2 and 61, in that order: #F4A261. How to do that conversion is in the hexadecimal system section.
Writing a result without its base in the exam. If you put «10100010» and the question had numbers in three bases, the marker does not have to guess what you meant. Subscript, always.
The octal system
Binary numbers are long and it is easy to make mistakes copying them (were there six ones or seven?). Octal is a compact way of writing them: base 8, digits 0 to 7 and weights that are powers of 8 (1, 8, 64, 512…).
The point is that : each octal digit is exactly 3 bits. So converting from binary to octal is as easy as grouping the bits in threes starting from the right (from the point) and replacing each trio by its digit:
Notice that the first group, on the left, only had two bits (11) and we put a 0 in front of it: zeros on the left do not change the value. And the other way round, from octal to binary, each digit is replaced by its 3 bits: .
Between octal and decimal you use the same as with binary, changing 2 for 8:
- Octal to decimal: sum of weights. .
- Decimal to octal: successive divisions by 8.
To count in octal, each wheel goes from 0 to 7: …6, 7, 10, 11… (octal «10» is eight). With m octal digits there are numbers, from 0 to . Octal is not seen much today; where it is still alive is in Linux permissions (chmod 755 is three octal digits of 3 bits each).
The hexadecimal system
Hexadecimal (or «hex») is the compact form most used: base 16, weights that are powers of 16 (1, 16, 256, 4096…) and sixteen digits. Since we only have ten numerals, the six missing ones are letters: A = 10, B = 11, C = 12, D = 13, E = 14 and F = 15. Counting: …9, A, B, C, D, E, F, 10, 11… 19, 1A… 1F, 20…
And here is the key: , so each hexadecimal digit is exactly 4 bits. A byte (8 bits) is always two hex digits. That is why colours are written in hexadecimal: each channel is 8 bits, that is, two hex digits.
- Binary to hex: groups of 4 bits from the point and each group by its digit: 1111 0100 = F4.
- Hex to binary: each digit by its 4 bits: .
- Hex to decimal: sum of weights. ; ; .
- Decimal to hex: successive divisions by 16 (a remainder from 10 to 15 is written with its letter). 244 / 16 = 15 remainder 4, and the quotient 15 is F: F4.
With m hex digits there are numbers. A full colour is 6 hex digits = 24 bits: colours, from #000000 (black) to #FFFFFF (white).
In hexadecimal, half a byte’s range is 80 (128), the maximum is FF (255) and 7F (127) is «almost half». If a channel starts with a high digit (C, D, E, F), that channel is strong; if it starts with 0 or 1, it barely contributes. That is how you read a colour at a glance: #F4A261 is lots of red, quite a lot of green and little blue, a soft orange.
The green, 162, to hexadecimal in two ways
To convert a channel to hexadecimal there are two ways, and it is worth doing both at least once to see that they end up in the same place.
Way 1, divisions by 16:
| Step | Working | Digit | Why |
|---|---|---|---|
| 1 | 162 divided by 16: 16 · 10 = 160, 2 left over | 2 | The remainder is the units digit, the one with weight 1 |
| 2 | The quotient is 10, less than 16 | A | No more divisions fit: the last quotient is the most significant digit, and 10 is written A |
| 3 | Last quotient and remainders from bottom to top | A2 | The same as with 2, only the divisor changes |
Way 2, going through binary: from the divisions by 2 you already have 162 = 10100010. Cut it into groups of 4 from the right, 1010 | 0010, and each group is a digit: 1010 is 10 (A) and 0010 is 2. A2 again, without dividing by 16.
A colour channel goes from 0 to 255, so in hexadecimal it is always two digits and one division by 16 is enough. To do it in your head, keep the 16 times table handy: 16, 32, 48, 64, 80, 96, 112, 128, 144, 160, 176, 192, 208, 224 and 240. Look for the highest multiple that does not go past the number: how many sixteens it is gives the first digit, and what is left over, the second. Red: 244 = 240 + 4, and 240 is 16 · 15, so F4. Green: 162 = 160 + 2, and 160 is 16 · 10, so A2. Blue: 97 = 96 + 1, and 96 is 16 · 6, so 61.
From octal to hexadecimal (and back): via binary
There is no direct shortcut between octal and hex, because 3 and 4 bits do not fit. But there is an indirect one that needs no divisions at all: go through binary and regroup. The whole colour, #F4A261, is 24 bits, and 24 is a multiple of both 3 and 4:
The same bits, cut in a different place. If the number of bits were not a multiple of 3, you would pad with zeros on the left, as before.
Grouping from the left. With 1011101 you would get 1011 101 = B5 (181), when the real value is 0101 1101 = 5D (93). The incomplete group has to end up on the left, where the zeros you add are worth nothing.
What about the fractional part?
You group outwards from the point: to the left in the integer part and to the right in the fractional part. And the padding zeros always go on the outside: on the left of the integer part and on the right of the fractional part (a 0 at the end of the fractional part does not change the value either). So , the 75 % opacity, in hexadecimal is 0.1100 = , not 0.3. We practice it calmly in the practice article.
The conversion map
With all the above, any conversion comes down to five recipes:
| I want to convert… | Method |
|---|---|
| From any base to decimal | Sum of weights: each digit times its power of the base |
| From decimal to binary (or octal, or hex) | Successive divisions by the base (integer part) and multiplications by the base (fractional part) |
| Between binary and octal | Groups of 3 bits from the point |
| Between binary and hexadecimal | Groups of 4 bits from the point |
| Between octal and hexadecimal | Via binary |
An exam tip: to convert a decimal number to hexadecimal, it is sometimes safer to divide by 2 (easy divisions) and group in 4s than to divide by 16 in your head. And the other way round: to convert hex to decimal, the sum of weights with powers of 16 is usually shorter than going through binary.
How many digits are needed?
It is a question that comes up a lot, sometimes hidden inside another one: how many bits do I need to store a number N? Look for the smallest m such that , that is, the first power of 2 that goes past the number.
For example, the phone gallery wants to number the photos of an album of 1000 photos in binary:
falls short (with 9 bits we reach 511) and goes past it: 10 bits are needed. In hexadecimal, every 4 bits are one digit: 10 bits need 3 hex digits (12 bits), and indeed .
Confusing «how many numbers» with «the largest number». With 8 bits there are 256 combinations, but the largest number is 255. To store the number 256 you need 9 bits.
The question, in words, is: what is the first number of bits whose «all ones» reaches N? With 8 bits, all ones is 255; with 9, 511; with 10, 1023. The first one that reaches 1000 is the 10-bit one. And to count hexadecimal digits you do the same with powers of 16: = 256 falls short of 1000 and = 4096 reaches it, so it is 3 digits, the same ones that 3E8 has.
Check you’ve got it: the album grows to 1024 photos. How many bits are needed if they are numbered from 0 to 1023? And if they are numbered from 1 to 1024?
From 0 to 1023, 10 bits are enough: the largest number is 1023, which is , all ones with 10 bits (1111111111). From 1 to 1024 you need 11 bits, even though it is the same 1024 photos: now the largest number is 1024 = , which in binary is a 1 followed by ten zeros, 10000000000. What decides the bits is not how many numbers there are, but the largest one you have to write. It is the same mistake as in the box above, the 256 with 8 bits.
Common mistakes
Reading the remainders of the divisions in the order they come out. The first remainder is the least significant bit: they are read from bottom to top, starting with the last quotient.
Treating the fractional part as an integer (converting 0.75 by dividing 75 by 2). The fractional part is multiplied by 2, and its digits are read from top to bottom.
Grouping the bits from the left, or padding with zeros on the wrong side. Always outwards from the point, and the padding zeros on the outside.
Using 8 or 9 as octal digits, or writing «12» instead of «C» for a remainder of a division by 16. Each base has B digits, from 0 to , and each position holds a single digit.
Writing numbers without stating the base, or giving instead of as the largest number with m digits.
Check it with Python
Python can do all these conversions out of the box (bin(), oct(), hex() and int(text, base)), but if you only use those functions you learn nothing for the exam. These two programs do the sums as on paper, showing each step, and at the end check the result with Python’s functions.
Successive divisions and multiplications
The first one reproduces the methods of the previous sections with the photo’s data: green (162) to binary, red (244) to octal and hexadecimal, and the two opacities (0.75 and 0.4) with 4 digits.
# Base conversion by hand, as on paper: successive divisions for the integer part
# and successive multiplications for the fractional part. Data from the sunset colour.
from fractions import Fraction # exact fractions: 0.4 is not rounded on the way
DIG = "0123456789ABCDEF" # digit 10 is A, 11 is B... up to F (15)
def integer_part(n, base):
remainders = []
print(f" {n} in base {base}:")
while n >= base: # divide while the quotient still allows another division
c, r = divmod(n, base)
print(f" {n:>4} / {base} = {c:>3} rem. {r:>2} ({DIG[r]})")
remainders.append(DIG[r]); n = c
print(f" last quotient: {n} ({DIG[n]})")
return DIG[n] + "".join(reversed(remainders)) # last quotient + remainders reversed
def fraction_part(f, base, digits):
f = Fraction(f); out = ""
print(f" 0.{str(float(f))[2:]} in base {base} with {digits} digits:")
for _ in range(digits):
x = f * base; d = int(x) # the integer part is the digit; carry on with what is left
print(f" {float(f):.4f} x {base} = {float(x):.4f} -> digit {DIG[d]}")
out += DIG[d]; f = x - d
if f == 0: break # exact: no need to go on
return out, f
print("Green channel, 162:", integer_part(162, 2))
print("Red channel, 244, in base 8:", integer_part(244, 8))
print("Red channel, 244, in base 16:", integer_part(244, 16))
for op, n in (("0.75", 4), ("0.4", 4)):
bits, rest = fraction_part(op, 2, n)
real = sum(Fraction(int(b), 2 ** (i + 1)) for i, b in enumerate(bits))
print(f" -> 0.{bits} (worth {float(real)}; error {float(Fraction(op) - real)})")
Output (run once):
162 in base 2:
162 / 2 = 81 rem. 0 (0)
81 / 2 = 40 rem. 1 (1)
40 / 2 = 20 rem. 0 (0)
20 / 2 = 10 rem. 0 (0)
10 / 2 = 5 rem. 0 (0)
5 / 2 = 2 rem. 1 (1)
2 / 2 = 1 rem. 0 (0)
last quotient: 1 (1)
Green channel, 162: 10100010
244 in base 8:
244 / 8 = 30 rem. 4 (4)
30 / 8 = 3 rem. 6 (6)
last quotient: 3 (3)
Red channel, 244, in base 8: 364
244 in base 16:
244 / 16 = 15 rem. 4 (4)
last quotient: 15 (F)
Red channel, 244, in base 16: F4
0.75 in base 2 with 4 digits:
0.7500 x 2 = 1.5000 -> digit 1
0.5000 x 2 = 1.0000 -> digit 1
-> 0.11 (worth 0.75; error 0.0)
0.4 in base 2 with 4 digits:
0.4000 x 2 = 0.8000 -> digit 0
0.8000 x 2 = 1.6000 -> digit 1
0.6000 x 2 = 1.2000 -> digit 1
0.2000 x 2 = 0.4000 -> digit 0
-> 0.0110 (worth 0.375; error 0.025)
Things to notice:
- For 162 to binary there are seven divisions and the last quotient is 1: with the remainders from bottom to top you get 10100010, as in the drawing.
- The same
integer_part()works for any base: 244 divided by 8 gives 364 and by 16 gives F4. Only the divisor changes, and in base 16 the remainder 15 is written as F (DIG[r]). - With 0.75 the loop stops by itself in the second round, because what is left is 0. With 0.4 it stops because the 4 digits run out, and the error comes out exactly 0.025.
- The program uses
Fractionso that 0.4 is not rounded on the way. If you usedfloat, 0.4 itself would already be stored with an error, which is exactly what this topic explains.
The colour in every base
The second one takes the eyedropper colour, #F4A261, splits it into channels and writes it in the four bases; then it makes the groups of 4 and 3 bits of the whole colour.
# The eyedropper colour, #F4A261, in the four bases and in groups of bits.
color = "F4A261"
channels = {"red": color[0:2], "green": color[2:4], "blue": color[4:6]}
for name, hx in channels.items():
n = int(hx, 16) # from hexadecimal to a number
print(f"{name:>5}: {hx} hex = {n:>3} dec = {n:08b} bin = {n:03o} oct")
bits = "".join(f"{int(h, 16):04b}" for h in color) # each hex digit is 4 bits
print("24 bits :", bits)
print("in 4s :", " ".join(bits[i:i + 4] for i in range(0, 24, 4)))
print("in 3s :", " ".join(bits[i:i + 3] for i in range(0, 24, 3)))
octal = "".join(str(int(bits[i:i + 3], 2)) for i in range(0, 24, 3))
print("in octal :", octal)
print("check :", oct(int(color, 16)), "=", int(color, 16), "dec")
print("colours with 24 bits:", 2 ** 24, "(from 0 to", 2 ** 24 - 1, ")")
print("one channel (8 bits) goes from 0 to", 2 ** 8 - 1)
red: F4 hex = 244 dec = 11110100 bin = 364 oct green: A2 hex = 162 dec = 10100010 bin = 242 oct blue: 61 hex = 97 dec = 01100001 bin = 141 oct 24 bits : 111101001010001001100001 in 4s : 1111 0100 1010 0010 0110 0001 in 3s : 111 101 001 010 001 001 100 001 in octal : 75121141 check : 0o75121141 = 16032353 dec colours with 24 bits: 16777216 (from 0 to 16777215 ) one channel (8 bits) goes from 0 to 255
Things to notice:
f"{n:08b}"writes the number in binary with 8 bits, padding with zeros on the left: blue, 97, comes out as 01100001 and not 1100001.- The groups of 4 bits read one by one are F, 4, A, 2, 6 and 1: the colour itself. The groups of 3 give 7, 5, 1, 2, 1, 1, 4 and 1.
- The check with
oct()gives 0o75121141, the same octal you get by grouping by hand, without a single division. - 2 to the 24 is 16777216 colours, and the largest, 16777215, is FFFFFF: «how many» and «the largest» differ by one.
Try it in the One number, every form simulator: you type a number and see it in binary, octal and hexadecimal at once, with the successive divisions and multiplications step by step and a warning when the fractional part never ends.
Summary
| Concept | The essentials |
|---|---|
| Positional system | Value = sum of each digit times its weight; the weight is a power of the base |
| Base B | B digits, from 0 to |
| Range with m digits | numbers, from 0 to |
| Binary | Base 2; weights …8, 4, 2, 1, 0.5, 0.25…; MSB on the left, LSB on the right |
| Octal | Base 8; 1 digit = 3 bits |
| Hexadecimal | Base 16; A-F = 10-15; 1 digit = 4 bits; 1 byte = 2 digits |
| To decimal | Sum of weights (in binary, only the weights of the 1s) |
| From decimal | Successive divisions (integer part, remainders from bottom to top) and multiplications (fractional part, from top to bottom) |
| Between 2, 8 and 16 | Groups of 3 or 4 bits from the point; between 8 and 16, via binary |
| Representation error | What is lost when cutting a periodic fraction at n digits |
| Bits needed for N | The smallest m with |
Three ideas to take away
- A number is digits plus a base. Without the base, «244» can be 244, 580 or 164: always write it.
- Everything comes from one formula, each digit times its weight: applying it is converting to decimal, and undoing it (divisions and multiplications) is converting from decimal.
- Octal and hexadecimal are binary written short: 3 and 4 bits per digit, grouped from the point. That is why hex is in colours, in memory addresses and in QtSpim.
Now it is time to practice. In the number systems practice we solve four problems step by step: converting to decimal from any base, a number with a point to binary with its error, conversions between binary, octal and hexadecimal, and a question in the format of the written exam. And once you have mastered it, the next topic is binary arithmetic: adding, subtracting and representing negative numbers with these same bits.
Next step: practiceNumber systems — practice with guided problems step by step: from any base to decimal, binary with a point, groups of bits and a question in the exam format (and the fraction I divided as if it were an integer)Did this article help you? Here is how you can support SergioLearns →



