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.

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: 232^3 = 2 · 2 · 2 = 8, any number to the power of 0 is 1, and a negative exponent means dividing (2−12^{-1} = 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 B−1B – 1. 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.

A positional systemThe same digit 3 is worth 3, 30 or 300 depending on its position, because each position has a weight that is a power of the base.3the 3 weighs10⁰ = 1it is worth 330the 3 weighs10¹ = 10it is worth 30300the 3 weighs10² = 100it is worth 300Same digit, different position, different valuevalue = Σ digit × base^position
What changes from one card to the next is not the digit but its weight.

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:

N=∑i=−nm−1di⋅Bi=⋯+d1B1+d0B0+d−1B−1+d−2B−2+… N = \sum_{i=-n}^{m-1} d_i \cdot B^i = \dots + d_1 B^1 + d_0 B^0 + d_{-1} B^{-1} + d_{-2} B^{-2} + \dots

where did_i is the digit in position i, B is the base and BiB^i 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 (B1,B2B^1, B^2…) and to the right they go down (B−1,B−2B^{-1}, B^{-2}…).

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:

PositionDigitWeightAddsWhy
22100 (10210^2)200It is two slots to the left of the units: multiplied by the base twice
1410 (10110^1)40One slot to the left: multiplied by the base once
041 (10010^0)4It is the units slot, and B0B^0 = 1 in any base
244The 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 B−1B^{-1} = 1/B, the second B−2B^{-2}, 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:

Digit4096.25
Weight10310^310210^210110^110010^010−110^{-1}10−210^{-2}
4096.25=4⋅1000+0⋅100+9⋅10+6⋅1+2⋅0.1+5⋅0.01 4096.25 = 4 \cdot 1000 + 0 \cdot 100 + 9 \cdot 10 + 6 \cdot 1 + 2 \cdot 0.1 + 5 \cdot 0.01

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 (102=10010^2 = 100 numbers) and with 3, 999. In general:

with m decimal digits: 10m numbers, from 0 to 10m−1 \text{with } m \text{ decimal digits: } 10^m \text{ numbers, from } 0 \text{ to } 10^m – 1

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:

Position76543210.−1−2−3
Weight12864321684210.50.250.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…

Counting in binary and the rangesOn the left, going from 0110 to 0111 and to 1000 like an odometer; on the right, the rule for m digits in base B and its range, with examples in binary and hexadecimal.0110= 60111= 71000= 8going from 0111 to 1000, the three 1s go back to 0and the carry turns on the next digitWith m digits in base BBᵐ numbers: 0 to Bᵐ − 1mbinaryhex10 … 10 … 1540 … 150 … 6553580 … 2550 … 2³² − 1240 … 16777215—
Counting works the same in every base: when a digit goes past its maximum, it goes back to 0 and carries one.

With m bits there are 2m2^m combinations, from 0 to 2m−12^m – 1. 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:

DecimalBinaryOctalHexDecimalBinaryOctalHex
000000081000108
100011191001119
200102210101012A
300113311101113B
401004412110014C
501015513110115D
601106614111016E
701117715111117F

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 2m2^m 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.

BitsCombinationsFrom 0 toWhy
121Just 0 or 1
243The previous 2 with a 0 in front (00, 01) and with a 1 in front (10, 11)
387Double again: 4 with a 0 in front and 4 with a 1 in front
41615The 16 rows of the table above
8256255Doubling eight times: 282^8. 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 weights of a binary numberThe binary number 11110100.11 with the weight of each position, from 2 to the 7 down to 2 to the minus 2; adding the weights of the ones gives 244.75.2⁷11282⁶1642⁵1322⁴1162³082²142¹022⁰012⁻¹10.52⁻²10.25,MSBLSB128 + 64 + 32 + 16 + 4 + 0.5 + 0.25 = 244.75only the weights of the 1s are added; the 0s add nothing
Left of the point, positive powers; right of it, negative ones (halves, quarters…).
11110100.11(2)=128+64+32+16+4+0.5+0.25=244.75(10) 11110100.11_{(2)} = 128 + 64 + 32 + 16 + 4 + 0.5 + 0.25 = 244.75_{(10)}

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:

LeftLargest power that fitsRemainder
244128 (272^7)116
11664 (262^6)52
5232 (252^5)20
2016 (242^4)4
44 (222^2)0

We used 27,26,25,242^7, 2^6, 2^5, 2^4 and 222^2: 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 (262^6), leaving 33; 32 (252^5) fits in 33, leaving 1; 1 (202^0) 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:

Successive divisions: 162 to binarySeven divisions of 162 by 2; the remainders and the last quotient, read from bottom to top, give 10100010.162 / 2 =81rem.081 / 2 =40rem.140 / 2 =20rem.020 / 2 =10rem.010 / 2 =5rem.05 / 2 =2rem.12 / 2 =1rem.011← last quotient (most significant digit)read from bottom to top162 = 10100010(in base 2)
The first remainder is the least significant bit; the last quotient, the most significant.
162(10)=10100010(2) 162_{(10)} = 10100010_{(2)}

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:

NumberIn binaryDivided by 2RemainderWhy
16210100010810162 is even: its units bit is 0
81101000140181 is 162 without its last bit, and it is odd: the next bit is 1
40101000200Again the last bit is removed and the remainder is that bit
2010100100Same
10101050Same
510121Odd: the bit that goes is a 1
21010Same
11It 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 multiplyResultDigitCarry on with
0.75 × 21.510.5
0.5 × 21.010 (end)
0.75(10)=0.11(2) 0.75_{(10)} = 0.11_{(2)}

Exact: 0.5 + 0.25 = 0.75. But now try an opacity of 0.4:

Successive multiplications: 0.4 to binaryFive multiplications of 0.4 by 2: the digits 0, 1, 1, 0, 0 come out and 0.4 appears again, so the sequence 0110 repeats forever.0.4 × 2 =0.80.8 × 2 =1.60.6 × 2 =1.20.2 × 2 =0.40.4 × 2 =0.8read from top to bottom0.4 → 0.01100…after 4 rounds 0.4 comes back:the digits 0110 repeat foreverwith 4 digits: 0.0110 = 0.375error = 0.4 − 0.375 = 0.025
The integer part of each product is a digit; what is left keeps being multiplied.

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, 0.4−0.375=0.0250.4 – 0.375 = 0.025, 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 multiplyResultDigitCarry on withWhy
0.4 × 20.800.80.4 does not reach a half: the 0.5 slot is not used
0.8 × 21.610.60.8 does go past a half: the 0.25 slot is used
0.6 × 21.210.2It goes past again: the 0.125 slot is used
0.2 × 20.400.4It 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:

  • 244(10)244_{(10)}: two hundred and forty-four.
  • 244(16)244_{(16)}: 2⋅256+4⋅16+4=5802 \cdot 256 + 4 \cdot 16 + 4 = 580.
  • 244(8)244_{(8)}: 2⋅64+4⋅8+4=1642 \cdot 64 + 4 \cdot 8 + 4 = 164.

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: 1110(2)=14(10)1110_{(2)} = 14_{(10)}, whereas 1110(10)1110_{(10)} 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.

Forgetting the baseOn the left, the sunset colour F4A261; on the right, the navy blue 244162 you get by typing the decimal values as if they were hexadecimal.#F4A261what I wanted#244162what I typed244 162 97stuck together as hex244₁₀ = F4₁₆, but 24₁₆ = 36₁₀: red went from 244 to 36
Same digits, another base, another colour.

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.

ChannelDigits it readValue it tookWhat I wantedWhy
Red242 · 16 + 4 = 36F4 = 244It read my digits as hexadecimal and cut them in a different place
Green414 · 16 + 1 = 65A2 = 162The 4 at the end of the red and the 1 of the green ended up together
Blue626 · 16 + 2 = 9861 = 97It 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 8=238 = 2^3: 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:

11110100(2)  →  011∣110∣100  →  3∣6∣4  →  364(8) 11110100_{(2)} \;\rightarrow\; 011 \mid 110 \mid 100 \;\rightarrow\; 3 \mid 6 \mid 4 \;\rightarrow\; 364_{(8)}

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: 364(8)=011 110 100(2)364_{(8)} = 011\,110\,100_{(2)}.

Between octal and decimal you use the same as with binary, changing 2 for 8:

  • Octal to decimal: sum of weights. 364(8)=3⋅64+6⋅8+4⋅1=192+48+4=244364_{(8)} = 3 \cdot 64 + 6 \cdot 8 + 4 \cdot 1 = 192 + 48 + 4 = 244.
  • Decimal to octal: successive divisions by 8.
244 to octal: divisions by 8Two divisions of 244 by 8 give the remainders 4 and 6 and the quotient 3: 364 in octal.244 / 8 =30rem.430 / 8 =3rem.633← last quotient (most significant digit)read from bottom to top244 = 364(in base 8)
Same method as with 2, just changing the divisor for the base.

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 8m8^m numbers, from 0 to 8m−18^m – 1. 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: 16=2416 = 2^4, 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.

The eyedropper colourThe colour F4A261 split into its three channels: red F4 = 244 = 11110100, green A2 = 162 = 10100010 and blue 61 = 97 = 01100001.#F4A261the sunset skyredF4=244=11110100greenA2=162=10100010blue61=97=011000012 hex digits = 8 bits = 0 to 255 per channel
The same colour written three ways: the editor shows the hex, the screen works with the bits.
  • 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: A2(16)=1010 0010(2)\mathrm{A2}_{(16)} = 1010\,0010_{(2)}.
  • Hex to decimal: sum of weights. F4(16)=15⋅16+4=244\mathrm{F4}_{(16)} = 15 \cdot 16 + 4 = 244; A2=10⋅16+2=162\mathrm{A2} = 10 \cdot 16 + 2 = 162; 61=6⋅16+1=9761 = 6 \cdot 16 + 1 = 97.
  • 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 16m16^m numbers. A full colour is 6 hex digits = 24 bits: 224=16 777 2162^{24} = 16\,777\,216 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:

StepWorkingDigitWhy
1162 divided by 16: 16 · 10 = 160, 2 left over2The remainder is the units digit, the one with weight 1
2The quotient is 10, less than 16ANo more divisions fit: the last quotient is the most significant digit, and 10 is written A
3Last quotient and remainders from bottom to topA2The 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 24 bits, grouped in two waysThe 24 bits of the colour F4A261: above in groups of four, giving the hex digits F, 4, A, 2, 6 and 1; below in groups of three, giving the octal digits 7, 5, 1, 2, 1, 1, 4 and 1.F4A261in 4s → hexadecimal11110100101000100110000175121141in 3s → octalF4A261₁₆ = 111101001010001001100001₂ = 75121141₈24 bits: exactly 6 groups of 4 and 8 groups of 3
Not a single division: just cut the strip of bits somewhere else.
F4A261(16)=111101001010001001100001(2)=75121141(8) \mathrm{F4A261}_{(16)} = 111101001010001001100001_{(2)} = 75121141_{(8)}

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 0.11(2)0.11_{(2)}, the 75 % opacity, in hexadecimal is 0.1100 = 0.C(16)\mathrm{0.C}_{(16)}, 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:

Conversion mapThe four bases linked by the method for each conversion: decimal and binary by divisions and sum of weights, binary and octal by groups of three, binary and hexadecimal by groups of four, and from octal or hexadecimal to decimal by sum of weights.decimal (10)binary (2)octal (8)hexadecimal (16)divisions /multiplicationssum of weightsgroups of 3groups of 4sum of weights (8ⁱ)sum of weights (16ⁱ)octal ↔ hexadecimal: always via binarydecimal → octal or hex: divide by 8 or by 16 (or go via binary)
Binary sits in the middle: almost every short route goes through it.
I want to convert…Method
From any base to decimalSum 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 octalGroups of 3 bits from the point
Between binary and hexadecimalGroups of 4 bits from the point
Between octal and hexadecimalVia 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 2m−1≥N2^m – 1 \ge N, 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:

How many bits are needed?Number line with the powers 256, 512 and 1024: the number 1000 falls between 512 and 1024, so 10 bits are needed.2⁸ = 2562⁹ = 5122¹⁰ = 10241000 photoswith 9 bits I reach 511: not enough; with 10 bits I reach 1023: yesrule: the smallest m with 2ᵐ − 1 ≥ N (here, 2ᵐ > 1000)
Look for the first power of 2 past the number: its exponent is the number of bits.

29=5122^9 = 512 falls short (with 9 bits we reach 511) and 210=10242^{10} = 1024 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 1000(10)=3E8(16)1000_{(10)} = \mathrm{3E8}_{(16)}.

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: 16216^2 = 256 falls short of 1000 and 16316^3 = 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 210−12^{10} – 1, 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 = 2102^{10}, 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 B−1B – 1, and each position holds a single digit.

Writing numbers without stating the base, or giving BmB^m instead of Bm−1B^m – 1 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:

  1. 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.
  2. 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]).
  3. 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.
  4. The program uses Fraction so that 0.4 is not rounded on the way. If you used float, 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:

  1. 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.
  2. 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.
  3. The check with oct() gives 0o75121141, the same octal you get by grouping by hand, without a single division.
  4. 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

ConceptThe essentials
Positional systemValue = sum of each digit times its weight; the weight is a power of the base
Base BB digits, from 0 to B−1B – 1
Range with m digitsBmB^m numbers, from 0 to Bm−1B^m – 1
BinaryBase 2; weights …8, 4, 2, 1, 0.5, 0.25…; MSB on the left, LSB on the right
OctalBase 8; 1 digit = 3 bits
HexadecimalBase 16; A-F = 10-15; 1 digit = 4 bits; 1 byte = 2 digits
To decimalSum of weights (in binary, only the weights of the 1s)
From decimalSuccessive divisions (integer part, remainders from bottom to top) and multiplications (fractional part, from top to bottom)
Between 2, 8 and 16Groups of 3 or 4 bits from the point; between 8 and 16, via binary
Representation errorWhat is lost when cutting a periodic fraction at n digits
Bits needed for NThe smallest m with 2m−1≥N2^m – 1 \ge N

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 →