ICS3U Computer Science • Ontario Grade 11

Corrected exercises: data representation, binary, hexadecimal, ASCII and Unicode (ICS3U)

Exercises: data representation, binary, hexadecimal, ASCII and Unicode (ICS3U)

Name: Class: Date:

Solutions

Suggested time: 2 h 30 · No calculator · 12 exercises
https://www.letuteurscientifique.ca/en/exercices/ics3u-binary-hexadecimal-data-representation

These ten corrected exercises, preceded by two lists of direct conversions, cover the data representation chapter of ICS3U, Introduction to Computer Science, Grade 11, University Preparation, in Ontario: how a computer uses the binary and hexadecimal number systems, the ASCII code and Unicode to represent data internally and store information, and the storage-capacity units that go with them, bits and bytes, SI prefixes and binary prefixes, megabits and megabytes.

What the set covers, the traps it targets

The programs are in Python 3 (ord, chr, int(text, 16), loops with % and //); weights, codes and unit conversions work the same way in any language, and a line of the solutions says where Java behaves differently.

Exercise 0.1 converts ten numbers between binary and decimal, exercise 0.2 ten numbers to and from hexadecimal. By the end, you can read a byte by its positional weights and trace a program that does it, on a DIP switch (exercise 1), find the number of bits for a number of values and the test that reveals a wrong bound, on MIDI notes (exercise 2), trace the repeated division by 2 and by 16 (exercise 3), convert between hexadecimal and binary four bits at a time, on a MAC address (exercise 4), and tell a digit character from its value with ord and chr, on a sudoku checker (exercise 5). Part B explains why a 512 GB SSD shows 476.84 GiB (exercise 6), splits an RGB colour code and sizes an icon (exercise 7), corrects five statements (exercise 8), computes a download time from a speed in megabits per second (exercise 9), and writes a program that counts the bytes of a message in UTF-8 (exercise 10).

The thread of the set: a computer stores only bits; a pattern of bits means a number, a character or a colour according to the code that reads it, and every positional code is read by weights, powers of 2 or of 16, counted from the right. Five traps are named in the solutions: (1) reading the weights from the wrong side, or the remainders of the divisions in the wrong order, exercises 0.1, 1 and 3; (2) forgetting that one hexadecimal digit is four bits and a byte two hexadecimal digits, exercises 0.2, 4, 7 and 8; (3) taking the character '7', code 55, for the number 7, exercises 5, 8 and 10; (4) mixing kilo, 1000, and kibi, 1024, so that a drive seems to lose space, exercises 6 and 7; (5) reading a speed in megabits per second as megabytes per second, exercises 8 and 9. Also treated: n bits give 2 ** n values whose largest is 2 ** n - 1 (0.1, 2, 8), a test value that is a power of 2 (2), the empty string printed for 0 (3), the leading zeros of a byte (4, 7), and one character that takes several bytes (10).

Negative numbers in two's complement and decimal numbers in floating point go beyond this chapter, and the limits of these representations are studied in Grade 12 (ICS4U). No calculator is needed: every conversion, every trace and every size is worked out by hand, as on a unit test.

  • 12 corrected exercises • 120 points • 150 minutes
  • Self-checking, 110 answers
  • No calculator
Start exercise 0.1 The chapter sheet
Print

Print the homework or the solutions

The homework without solutions, one exercise per page, and the solutions on their own: it comes with your free space. An email is enough, no password, and you come back here.

Create my free space

Already have one? Sign in

Course recap

  • • Binary weights from the right: 1, 2, 4, 8, 16, 32, 64, 128; hexadecimal weights: 1, 16, 256, 4096.
  • • Decimal to binary: divide by 2 until the quotient is 0, then read the remainders from the last to the first.
  • • n bits give 2 ** n values, from 0 to 2 ** n - 1: one byte, 8 bits, holds 0 to 255.
  • • One hexadecimal digit stands for four bits; one byte is two hexadecimal digits, from 00 to FF. Group the bits by four from the right.
  • • ord(c) gives back the code of a character, chr(n) the character of a code; the digits '0' to '9' have the codes 48 to 57.
  • • ASCII is the codes 0 to 127; Unicode numbers every character, and UTF-8 stores one character on 1 to 4 bytes.
  • • kilo, mega, giga, tera are powers of 1000; kibi, mebi, gibi, tebi are powers of 1024.
  • • A speed in Mbps counts bits: divide by 8 for megabytes per second.

Calculations: binary and decimal

Exercise 0.1: Binary and decimal: ten conversions

10 answers to check

Convert each binary number to decimal, each decimal number to binary, or answer the question.

Method: in binary, the rightmost digit has the weight 1, and each place to the left doubles the weight: 1, 2, 4, 8, 16, 32, 64, 128. A binary number is the sum of the weights under its 1s. To go the other way, subtract the largest weight that fits, write 1 there, and carry on with what is left.

  • a) 1011 in decimal
  • b) 110010 in decimal
  • c) 1111111 (seven 1s) in decimal
  • d) 10000000 in decimal
  • e) 11101001 in decimal
  • f) 19 in binary
  • g) 100 in binary
  • h) 255 in binary
  • i) 64 in binary
  • j) The largest whole number that can be written with 6 bits, in decimal

Type your answers, the page tells you right or wrong 0/10

a)
b)
c)
d)
e)
f)
g)
h)
i)
j)
Show the solution

Answers

  • a) 11
  • b) 50
  • c) 127
  • d) 128
  • e) 233
  • f) 10011
  • g) 1100100
  • h) 11111111
  • i) 1000000
  • j) 63

Write the weights above the digits, starting with 1 above the rightmost digit, then add the weights that sit above a 1.

a)

Weights 8, 4, 2, 1 above 1, 0, 1, 1: 8 + 2 + 1 = 11.

Pitfall: giving the weight 1 to the leftmost digit, which reads 1101 and gives 13.

b)

Weights 32, 16, 8, 4, 2, 1 above 1, 1, 0, 0, 1, 0: 32 + 16 + 2 = 50.

c)

64 + 32 + 16 + 8 + 4 + 2 + 1 = 127. Seven 1s are one less than the next weight, 128: 2 ** 7 - 1 = 127.

d)

A 1 followed by seven 0s has the weight 2 ** 7 = 128.

e)

Weights 128, 64, 32, 16, 8, 4, 2, 1 above 1, 1, 1, 0, 1, 0, 0, 1: 128 + 64 + 32 + 8 + 1 = 233.

f)

16 fits in 19, leaving 3; 8 and 4 do not fit; 2 fits, leaving 1; 1 fits: a 1 at the weights 16, 2 and 1, so 10011.

Check: 16 + 2 + 1 = 19.

g)

64 fits, leaving 36; 32 fits, leaving 4; 16 and 8 do not fit; 4 fits, leaving 0: 1100100.

Check: 64 + 32 + 4 = 100.

h)

255 = 128 + 64 + 32 + 16 + 8 + 4 + 2 + 1: eight 1s, 11111111. 255 is 2 ** 8 - 1, the largest value of one byte.

i)

64 = 2 ** 6: a 1 followed by six 0s, 1000000, seven digits.

j)

Six 1s: 32 + 16 + 8 + 4 + 2 + 1 = 63 = 2 ** 6 - 1. 6 bits give 2 ** 6 = 64 values, from 0 to 63.

Tick the exercises you have done or want to review: a free account, no password, keeps your ticks and your right answers from one visit to the next, tells you which chapter to tackle next and lets you ask for the exercise you are missing. Create your space, an email is enough.

Calculations: hexadecimal

Exercise 0.2: Hexadecimal: ten conversions

10 answers to check

Convert as asked. The hexadecimal digits are 0 to 9, then A, B, C, D, E and F for 10 to 15.

Method: in hexadecimal, the weights are 1, 16, 256, 4096 from the right. To go from decimal to hexadecimal, divide by 16: for a number under 256, the quotient is the left digit and the remainder the right digit. Between binary and hexadecimal, each hexadecimal digit stands for exactly four bits, grouped from the right.

  • a) 2A in decimal
  • b) FF in decimal
  • c) 100 (hexadecimal) in decimal
  • d) B7 in decimal
  • e) 7E3 in decimal
  • f) 200 in hexadecimal
  • g) 75 in hexadecimal
  • h) 11010110 (binary) in hexadecimal
  • i) 3F in binary, on 8 bits
  • j) The largest whole number written with three hexadecimal digits, in hexadecimal

Type your answers, the page tells you right or wrong 0/10

a)
b)
c)
d)
e)
f)
g)
h)
i)
j)
Show the solution

Answers

  • a) 42
  • b) 255
  • c) 256
  • d) 183
  • e) 2019
  • f) C8
  • g) 4B
  • h) D6
  • i) 0011 1111
  • j) FFF, that is 4095

Two digits are read with the weights 16 and 1, three digits with 256, 16 and 1. A letter is replaced by its value first: A = 10, B = 11, C = 12, D = 13, E = 14, F = 15.

a)

2 × 16 + 10 = 42.

b)

15 × 16 + 15 = 255: FF is the largest value of one byte, like 11111111.

c)

1 × 256 + 0 × 16 + 0 = 256. 100 in hexadecimal is not one hundred.

Pitfall: reading the digits of a hexadecimal number as if they were decimal.

d)

B = 11: 11 × 16 + 7 = 176 + 7 = 183.

e)

7 × 256 + 14 × 16 + 3 = 1792 + 224 + 3 = 2019.

f)

200 // 16 = 12 and 200 % 16 = 8: the digits 12 and 8, that is C8.

Check: 12 × 16 + 8 = 200.

g)

75 // 16 = 4 and 75 % 16 = 11: the digits 4 and B, so 4B.

Check: 4 × 16 + 11 = 75.

h)

Group the bits by four from the right: 1101 and 0110. 1101 = 8 + 4 + 1 = 13, that is D; 0110 = 4 + 2 = 6. So D6.

Check: 13 × 16 + 6 = 214, and 128 + 64 + 16 + 4 + 2 = 214.

i)

3 is 0011 and F is 1111: 0011 1111. The leading zeros keep the byte at 8 bits; its value is 63.

j)

Three F: FFF = 15 × 256 + 15 × 16 + 15 = 4095 = 16 ** 3 - 1. One more gives 1000 in hexadecimal, 4096.

Part A: the basics (/50)

Exercise 1: Positional weights: the byte set by a DIP switch

9 answers to check

A circuit board of a robotics kit gets its number from a DIP switch, a row of eight small levers: a lever up is a 1, a lever down is a 0. The figure shows the switch. The board's program reads the levers from left to right as a string, then computes the number they set.

up: 1down: 0The eight levers, read from left to right
Python
levers = '01101001'             # line 1
value = 0                       # line 2
for ch in levers:               # line 3
    value = value * 2 + int(ch) # line 4
print(value)                    # line 5
  • a) Write the weight of each lever, then give the number set by the switch.
  • b) What does value hold at the end of the fifth pass of the loop? How many passes does the loop make?
  • c) A classmate writes weight = 1 before the loop, then value = value + int(ch) * weight and weight = weight * 2 inside it. What does his program print? Which lever gets the weight 1 in his version?
  • d) Each lever is moved one place to the left: the leftmost one leaves the switch and the rightmost place gets a 0, which gives 11010010. What number does the switch set now? How does it compare with the number of question a)?
  • e) What is the largest number the switch can set? How many different numbers can it set?

Type your answers, the page tells you right or wrong 0/9

a)
b)
c)
d)
e)
Show the solution

Answers

  • a) Weights 128, 64, 32, 16, 8, 4, 2, 1; 64 + 32 + 8 + 1 = 105
  • b) 13; 8 passes
  • c) 150; the leftmost lever
  • d) 210, twice 105
  • e) 255; 256 numbers, from 0 to 255

The weight of a lever depends on its place counted from the RIGHT: 1 for the rightmost lever, then 2, 4, 8, and so on up to 128 for the leftmost one. Line 4 reaches the same sum another way: each pass doubles what has been read so far, which moves every earlier bit up one weight, then adds the new bit.

a)

From left to right, the weights are 128, 64, 32, 16, 8, 4, 2, 1, above the bits 0, 1, 1, 0, 1, 0, 0, 1.

The levers up have the weights 64, 32, 8 and 1: 64 + 32 + 8 + 1 = 105. The table below adds them.

b)

value goes 0 × 2 + 0 = 0, then 0 × 2 + 1 = 1, 1 × 2 + 1 = 3, 3 × 2 + 0 = 6, 6 × 2 + 1 = 13: 13 after the fifth pass.

There is one pass per character, 8 passes; the last three give 26, 52 and 105, the number of question a).

c)

His weight 1 goes to the first character read, the LEFTMOST lever, then 2, 4, up to 128 for the rightmost one: he reads 01101001 as if it were 10010110.

0 × 1 + 1 × 2 + 1 × 4 + 0 × 8 + 1 × 16 + 0 × 32 + 0 × 64 + 1 × 128 = 2 + 4 + 16 + 128 = 150.

Pitfall: reading the weights from the wrong side. A string is read from the left, and the weights grow from the right.

d)

11010010: 128 + 64 + 16 + 2 = 210, that is 2 × 105. Moving every bit one place to the left doubles each weight, so it doubles the number.

Here the leftmost lever was a 0. A 1 there would have left the switch, and the number would not have doubled: the limits of a representation on a fixed number of bits are studied in Grade 12 (ICS4U).

e)

All the levers up: 11111111 = 255. Each lever has 2 positions, so 8 levers give 2 ** 8 = 256 settings, the numbers 0 to 255.

How a computer stores negative whole numbers (two's complement) or decimal numbers (floating point) goes beyond this chapter.

Weight1286432168421Lever01101001Adds0643208001Weights from the right: 64 + 32 + 8 + 1 = 105

Exercise 2: How many bits for n values: notes in MIDI

11 answers to check

MIDI, the standard that lets electronic instruments and computers exchange music, sends each note number as a 7-bit value, and the velocity of a note, how hard the key is struck, as another 7-bit value. A pitch-bend wheel is sent as a 14-bit value. The program below gives the smallest number of bits that can store a given number of values, numbered from 0.

Python
values = int(input('Number of values: '))  # line 1
bits = 0                                    # line 2
while 2 ** bits < values:                   # line 3
    bits = bits + 1                         # line 4
print(bits, 'bits')                         # line 5
  • a) How many different values can 7 bits hold? What is the largest one? How many values can a 14-bit pitch bend take?
  • b) A piano has 88 keys. What does the program print for 88? Why are 6 bits too few?
  • c) A keyboard has 61 keys. What does the program print for 61?
  • d) A MIDI message carries a channel numbered 1 to 16 on the screen, on 4 bits. How many bits does the number 16 itself take in binary? How are the 16 channels stored on 4 bits?
  • e) A student writes while 2 ** bits <= values: on line 3. What does his program print for 88, and for 128? Which of these two tests reveals the bug?

Type your answers, the page tells you right or wrong 0/11

a)
b)
c)
d)
e)
Show the solution

Answers

  • a) 128 values; 127; 16384 values
  • b) 7 bits; 6 bits give 64 values, fewer than 88
  • c) 6 bits
  • d) 5 bits (10000); as 0 to 15, the channel minus 1
  • e) 7 bits and 8 bits; the test with 128, a power of 2

n bits give 2 ** n different patterns, so 2 ** n values, numbered from 0 to 2 ** n - 1. The number of bits for a number of values is the smallest n with 2 ** n at least equal to that number: the loop of line 3 doubles the capacity until it is enough. The table below gives the capacities from 4 to 8 bits.

a)

2 ** 7 = 128 values, from 0 to 127: the largest is 127.

14 bits give 2 ** 14 = 16384 values, from 0 to 16383.

b)

The loop stops at the first n with 2 ** n ≥ 88: 2 ** 6 = 64 < 88, but 2 ** 7 = 128 ≥ 88. The program prints 7 bits.

6 bits give 64 values only: 24 of the keys would have no number. MIDI's 7 bits are enough for a piano, whose keys use the note numbers 21 to 108, that is 108 - 21 + 1 = 88 numbers.

c)

2 ** 5 = 32 < 61 and 2 ** 6 = 64 ≥ 61: 6 bits.

d)

16 = 2 ** 4 is a 1 followed by four 0s, 10000: 5 bits. The number of values and the largest value are not the same thing.

16 values fit in 4 bits when they are numbered from 0: the channels 1 to 16 are stored as 0 to 15, the channel number minus 1, and 15 is 1111.

Pitfall: sizing a field for the largest number shown on the screen when the values are counted from 0.

e)

With <=, the loop also goes on when 2 ** bits equals values. For 88 nothing changes: 2 ** 7 = 128 is not equal to 88, and the program prints 7 bits. For 128, at bits = 7 the test 128 <= 128 is True, so the loop goes one step further and prints 8 bits, one bit too many.

Only a test with a power of 2 reveals the bug: a test plan for a loop bound includes the value where < and <= differ.

BitsValuesRange4160 to 155320 to 316640 to 6371280 to 12782560 to 25564 values are too few for 88 keys; 128 are enough

Exercise 3: Repeated division by 2: tracing a conversion program

9 answers to check

The program below converts a positive whole number to binary by repeated division by 2. Each remainder n % 2 is one bit, and the quotient n // 2 is divided again until it reaches 0.

Python
n = int(input('Whole number: '))    # line 1
bits = ''                           # line 2
while n > 0:                        # line 3
    bits = str(n % 2) + bits        # line 4
    n = n // 2                      # line 5
print(bits)                         # line 6
  • a) What does line 6 print for 77?
  • b) How many passes does the loop make for 77? What does bits hold at the end of the third pass?
  • c) A classmate writes bits = bits + str(n % 2) on line 4. What does his program print for 77? What number does that binary string stand for?
  • d) What does the program print when the user types 0? Which lines, added just before line 6, correct it?
  • e) Line 4 becomes bits = '0123456789ABCDEF'[n % 16] + bits and line 5 becomes n = n // 16. What does the program print for 77, and for 500?

Type your answers, the page tells you right or wrong 0/9

a)
b)
c)
d)
e)
Show the solution

Answers

  • a) 1001101
  • b) 7 passes; '101'
  • c) 1011001, which stands for 89
  • d) An empty line; if bits == '': bits = '0'
  • e) 4D; 1F4

The first remainder is the bit of weight 1, the rightmost bit; each later remainder belongs one place further LEFT. That is why line 4 puts the new bit in front of the string. The trace table below follows the seven passes for 77; the corrected program is below it.

a)

The remainders, in order: 1, 0, 1, 1, 0, 0, 1. Each one goes in front of the others, so the string reads them from the last to the first: 1001101.

Check by the weights: 64 + 8 + 4 + 1 = 77.

b)

n takes the values 77, 38, 19, 9, 4, 2, 1, then 0, which stops the loop: 7 passes, one per bit.

Pass 1 gives '1', pass 2 gives '01', pass 3 gives '101'.

c)

bits + str(n % 2) puts each remainder at the END: the string keeps the remainders in their order of arrival, 1011001, the right answer backwards.

1011001 = 64 + 16 + 8 + 1 = 89, not 77, and no error warns about it.

Pitfall: reading the remainders from the first to the last. The first remainder is the rightmost bit.

d)

For 0, the test n > 0 is False at once: the loop never runs, bits stays '', and line 6 prints an empty line.

if bits == '': bits = '0', placed before line 6, prints 0. A test plan for a conversion includes 0.

e)

In base 16 each remainder is a digit from 0 to 15, taken from the string of the sixteen digits. 77 % 16 = 13, written D, and 77 // 16 = 4; then 4 % 16 = 4 and 4 // 16 = 0: 4D. Check: 4 × 16 + 13 = 77.

500 % 16 = 4 and 500 // 16 = 31; 31 % 16 = 15, written F, and 31 // 16 = 1; 1 % 16 = 1: 1F4. Check: 256 + 15 × 16 + 4 = 500.

Python's built-in bin(77) gives '0b1001101', with the prefix 0b; on a unit test, the algorithm is what is asked.

Python
n = int(input('Whole number: '))
bits = ''
while n > 0:
    bits = str(n % 2) + bits    # the new bit goes in front
    n = n // 2
if bits == '':
    bits = '0'
print(bits)
Passnn % 2n // 2bits after the pass177138'1'238019'01'31919'101'4914'1101'5402'01101'6201'001101'7110'1001101'Each pass puts the new remainder in FRONT of bits

Exercise 4: Four bits per hexadecimal digit: reading a MAC address

9 answers to check

Every network card has a MAC address of 48 bits, which a computer displays as twelve hexadecimal digits in six pairs, one pair per byte. The figure shows the address 6E-2B-91-07-F4-D8.

6Ebyte 12Bbyte 291byte 307byte 4F4byte 5D8byte 6MAC address 6E-2B-91-07-F4-D8: six pairs of hexadecimal digits
  • a) How many bits does one hexadecimal digit stand for? How many bytes does the address take?
  • b) Write the byte F4 in binary.
  • c) A student writes the byte 07 as 111. Which 8-bit pattern is the byte really? How many 0s must he write in front of 111?
  • d) What is the byte 91 in decimal? Write the first byte, 6E, in binary.
  • e) How many different values can one byte take? How many different patterns can 48 bits form?

Type your answers, the page tells you right or wrong 0/9

a)
b)
c)
d)
e)
Show the solution

Answers

  • a) 4 bits; 6 bytes
  • b) 1111 0100
  • c) 0000 0111; 5 zeros
  • d) 145; 0110 1110
  • e) 256; 2 ** 48

One hexadecimal digit takes one of 16 values, and 16 = 2 ** 4: it stands for four bits, and a byte of eight bits is two hexadecimal digits. Converting between the two is done digit by digit, with no division at all.

a)

48 bits / 4 = 12 hexadecimal digits, which is what the address shows. 48 bits / 8 = 6 bytes, one per pair.

Pitfall: counting one byte per hexadecimal digit, which gives 12 bytes, twice too many.

b)

F = 15 = 8 + 4 + 2 + 1, that is 1111; 4 = 0100. F4 is 1111 0100. The figure below shows the two groups.

Check: 128 + 64 + 32 + 16 + 4 = 244 = 15 × 16 + 4.

c)

The value 7 is right, but a byte has eight bits: 0 is 0000 and 7 is 0111, so 0000 0111. In front of 111, five 0s.

The leading zeros change nothing to the value; they keep every byte at the same width, which is what lets a program cut the address into bytes.

d)

91: 9 × 16 + 1 = 145.

6E: 6 = 0110 and E = 14 = 1110, so 0110 1110. Check: 64 + 32 + 8 + 4 + 2 = 110 = 6 × 16 + 14.

e)

One byte: 2 ** 8 = 256 values, from 00 to FF.

48 bits form 2 ** 48 patterns: each extra bit doubles the count. 48 ** 2 would be the patterns of two choices among 48, not of 48 bits.

11110100F = 154Each hexadecimal digit becomes exactly four bits:F4 is 1111 0100, and 07 is 0000 0111, never 111

Exercise 5: The character '7' is not the number 7: a sudoku row checker

9 answers to check

In a solved sudoku, each row holds the digits 1 to 9 once, so its digits add up to 45. A program reads a row typed as nine digits and checks that sum. ord(c) gives back the code of the character c, and chr(n) the character whose code is n; the figure gives an excerpt of the ASCII table, whose codes Unicode keeps. The first test, on the row 534678912, fails.

Character'.''/''0''1''2''3''4''5''6''7''8''9'Code464748495051525354555657An excerpt of the ASCII table (codes in decimal)
Python
row = input('Row of 9 digits: ')    # line 1
total = 0                           # line 2
for ch in row:                      # line 3
    total = total + ord(ch)         # line 4
if total == 45:                     # line 5
    print('Sum OK')                 # line 6
else:                               # line 7
    print('Sum wrong:', total)      # line 8
  • a) Give ord('0') and ord('5'). What does ord('9') - ord('0') give?
  • b) What does the program print for the row 534678912?
  • c) Which line 4 corrects the program? What does it print then for 534678912?
  • d) With that correction, a player types a dot for an empty cell: 53.678912. What does the program print?
  • e) The missing digit of 53.678912 is 45 minus the sum of the eight other digits. What is it? Which expression gives back the character of a digit d, from 0 to 9?

Type your answers, the page tells you right or wrong 0/9

a)
b)
c)
d)
e)
Show the solution

Answers

  • a) 48 and 53; 9
  • b) Sum wrong: 477
  • c) total = total + ord(ch) - ord('0'); Sum OK
  • d) Sum wrong: 39
  • e) 4; chr(ord('0') + d)

input() gives back characters, and a character is stored as its code: the character '5' is the code 53, not the number 5. The digits '0' to '9' have the codes 48 to 57 in a row, so ord(ch) - ord('0') gives back the value of a digit. The corrected program is below.

a)

The table gives ord('0') = 48 and ord('5') = 53.

ord('9') - ord('0') = 57 - 48 = 9: the codes of the digits follow each other, so the gap between two codes is the gap between the digits.

b)

Line 4 adds the codes 53, 51, 52, 54, 55, 56, 57, 49, 50. Each code is its digit plus 48, so the total is 45 + 9 × 48 = 45 + 432 = 477.

477 is not 45: the program prints Sum wrong: 477.

Pitfall: taking ord(ch) for the value of the digit ch. It gives back its code.

c)

total = total + ord(ch) - ord('0') adds 5, then 3, and so on: the total is 45, and the program prints Sum OK.

total = total + int(ch) works as well. ord(ch - '0') stops the program: - between two strings is a TypeError.

In Java, a char is a number: ch - '0' gives the digit directly, and '7' + 1 gives 56.

d)

The dot has the code 46, so ord('.') - ord('0') = 46 - 48 = -2: the program adds -2 for the empty cell, without any error.

5 + 3 - 2 + 6 + 7 + 8 + 9 + 1 + 2 = 39: Sum wrong: 39. A program that reads digits checks that each code lies from 48 to 57 before using it.

e)

The eight digits add up to 5 + 3 + 6 + 7 + 8 + 9 + 1 + 2 = 41, so the missing digit is 45 - 41 = 4.

The character of a digit d has the code 48 + d: chr(ord('0') + d) gives '4' for d = 4. chr(4) gives back the character of code 4, a control character, not '4'.

Python
row = input('Row of 9 digits: ')
total = 0
for ch in row:
    total = total + ord(ch) - ord('0')   # the digit, not its code
if total == 45:
    print('Sum OK')
else:
    print('Sum wrong:', total)

Part B: problems and reasoning (/50)

Exercise 6: Kilo or kibi: the SSD that seems to shrink

8 answers to check

A laptop is sold with a 512 GB SSD. The maker counts with the SI prefixes, in powers of 1000; the laptop's operating system counts in powers of 1024, the binary prefixes kibi, mebi, gibi, shown in the table. A student checks the two numbers with a short program.

SI prefixBytesBinary prefixByteskilo, kB1000kibi, KiB1024mega, MB1000000mebi, MiB1048576giga, GB1000000000gibi, GiB1073741824tera, TB1000000000000tebi, TiB1099511627776Bytes in one unit: SI prefixes and binary prefixes
Python
capacity = 512 * 1000 ** 3              # line 1: bytes, as on the box
print(capacity)                         # line 2
print(capacity / 1024 ** 3)             # line 3
print(round(capacity / 1024 ** 3, 2))   # line 4
  • a) What does line 2 print?
  • b) Line 3 prints 476.837158203125. In which unit is that number a capacity? What does line 4 print?
  • c) The student concludes that about 35 GB are missing from the SSD. Is he right?
  • d) How many bytes are 64 KiB? And 3 MiB?
  • e) A file holds 2097152 bytes. What is its size in MiB? In MB, to the hundredth?

Type your answers, the page tells you right or wrong 0/8

a)
b)
c)
d)
e)
Show the solution

Answers

  • a) 512000000000
  • b) GiB; 476.84
  • c) No: the same bytes are counted in a larger unit
  • d) 65536 bytes; 3145728 bytes
  • e) 2 MiB; 2.10 MB

The two systems count the same bytes. A gibibyte, 1024 ** 3 = 1073741824 bytes, is larger than a gigabyte, 1000 ** 3 = 1000000000 bytes, so the same capacity is a smaller number of GiB than of GB. The table below gives the gap for each prefix.

a)

512 × 1000 ** 3 = 512 × 1000000000 = 512000000000 bytes: line 2 prints 512000000000.

b)

Line 3 divides by 1024 ** 3, the number of bytes in one gibibyte: 476.837158203125 is the capacity in GiB.

round(..., 2) keeps two decimals: line 4 prints 476.84.

c)

No. The SSD holds 512000000000 bytes either way: 512 GB and 476.84 GiB are the same capacity in two units, as 1 m and 100 cm are the same length.

The gap, 512 - 476.84 = 35.16, comes from the unit: a gibibyte is 1.074 times a gigabyte, so the number shown is about 6.9 % smaller.

Pitfall: comparing a number of GB with a number of GiB, or reading GiB as GB. Some systems display GiB under the label GB, which is where the confusion starts.

d)

64 KiB = 64 × 1024 = 65536 bytes.

3 MiB = 3 × 1024 × 1024 = 3 × 1048576 = 3145728 bytes.

e)

2097152 / 1048576 = 2: the file is exactly 2 MiB.

In MB: 2097152 / 1000000 = 2.097152, that is 2.10 MB to the hundredth. The same file reads 2 MiB in one window and 2.1 MB in another.

UnitsRatioSmaller bykilo against kibi1000 / 10242.3 %mega against mebi1000 ** 2 / 1024 ** 24.6 %giga against gibi1000 ** 3 / 1024 ** 36.9 %tera against tebi1000 ** 4 / 1024 ** 49.1 %The gap grows with each prefix

Exercise 7: RGB colours in hexadecimal: a colour picker

9 answers to check

A drawing app writes each colour in the form #RRGGBB: two hexadecimal digits for the red, two for the green, two for the blue, each component being one byte, from 0 to 255. The figure splits the colour #E85D04. Its colour picker converts a code into its three components; int(text, 16) gives back the whole number that text writes in base 16.

#E8red5Dgreen04bluethe colourA colour code: two hexadecimal digits per component
Python
colour = input('Colour (#RRGGBB): ')   # line 1
red = int(colour[1:3], 16)             # line 2
green = int(colour[3:5], 16)           # line 3
blue = int(colour[5:7], 16)            # line 4
print(red, green, blue)                # line 5
  • a) What does line 5 print for #E85D04?
  • b) A classmate writes red = int(colour[0:2], 16) on line 2. What happens?
  • c) How many bits does one colour take? How many different colours can the app write?
  • d) An icon of 64 by 64 pixels is stored without compression, one colour per pixel. How many bytes does it take? How many KiB?
  • e) Which code writes the colour with red 16, green 160 and blue 5?

Type your answers, the page tells you right or wrong 0/9

a)
b)
c)
d)
e)
Show the solution

Answers

  • a) 232 93 4
  • b) ValueError: int('#E', 16) is refused
  • c) 24 bits; 16777216 colours
  • d) 12288 bytes; 12 KiB
  • e) #10A005

Each pair of digits is one byte read with the weights 16 and 1, and the slices [1:3], [3:5], [5:7] take the pairs after the #. The table below converts the three pairs of #E85D04.

a)

E8 = 14 × 16 + 8 = 232; 5D = 5 × 16 + 13 = 93; 04 = 0 × 16 + 4 = 4. Line 5 prints 232 93 4: a lot of red, some green, almost no blue, an orange.

b)

colour[0:2] is '#E', and # is not a hexadecimal digit: int('#E', 16) stops the program with ValueError: invalid literal for int() with base 16: '#E'.

The slices start at index 1, after the #.

c)

3 components × 8 bits = 24 bits.

2 ** 24 = 2 ** 10 × 2 ** 10 × 2 ** 4 = 1024 × 1024 × 16 = 16777216 colours: 256 values per component, and 256 × 256 × 256 = 16777216.

d)

64 × 64 = 4096 pixels, 3 bytes each: 4096 × 3 = 12288 bytes.

12288 / 1024 = 12 KiB. In kB, the same icon is 12.288 kB.

e)

16 = 1 × 16 + 0, that is 10; 160 = 10 × 16 + 0, that is A0; 5 is 05, on two digits. The code is #10A005.

Pitfall: writing 5 as a single digit. #10A05 has five digits, and the app reads its pairs as 10, A0 and 5 with a digit missing. Each byte takes two hexadecimal digits, a leading 0 included; format(5, '02X') gives back '05'.

ComponentPairWeights 16 and 1ValueredE814 × 16 + 8232green5D5 × 16 + 1393blue040 × 16 + 44Each pair is one byte, from 0 to 255

Exercise 8: Five statements to correct

10 answers to check

Each statement below was written by a student revising this chapter. Say whether it is true or false, then answer the question that follows it. Each false statement is corrected in the solution.

  • a) « One hexadecimal digit takes one byte. » How many hexadecimal digits does one byte take?
  • b) « With 8 bits, a program can store every whole number from 0 to 256. » What is the largest whole number 8 bits can store?
  • c) « In Python, '4' + '3' gives '7'. » What does chr(ord('4') + 3) give back?
  • d) « A 100 Mbps connection downloads 100 MB every second. » How many MB per second does it download at that speed?
  • e) « Writing a 0 at the right end of a binary number doubles its value. » What is the value of 1011 followed by a 0?

Type your answers, the page tells you right or wrong 0/10

a)
b)
c)
d)
e)
Show the solution

Answers

  • a) False; 2 digits
  • b) False; 255
  • c) False; '7'
  • d) False; 12.5 MB
  • e) True; 10110 = 22

Each statement is settled by one exact count: bits in a digit, values on 8 bits, codes of two characters, bits in a byte, weights of a number.

a)

False. One hexadecimal digit stands for 4 bits, half a byte: a byte of 8 bits takes 2 hexadecimal digits, from 00 to FF.

Correct statement: « One hexadecimal digit stands for four bits; one byte takes two hexadecimal digits. »

b)

False. 8 bits give 2 ** 8 = 256 values, and the first one is 0: they go from 0 to 255. 256 is 100000000, which takes 9 bits.

Correct statement: « With 8 bits, a program can store every whole number from 0 to 255. »

c)

False. + joins two strings: '4' + '3' gives '43', two characters.

chr(ord('4') + 3) = chr(52 + 3) = chr(55), the character '7': the codes of the digits follow each other.

Correct statement: « In Python, '4' + '3' gives '43', and int('4') + int('3') gives 7. »

d)

False. Mbps counts megabits per second, and a byte is 8 bits: 100 / 8 = 12.5 MB per second, at the advertised speed.

Correct statement: « A 100 Mbps connection downloads at most 12.5 MB every second. »

e)

True. The 0 moves every digit one place to the left, and each weight doubles: 1011 is 11, and 10110 = 16 + 4 + 2 = 22 = 2 × 11.

The rule holds as long as the number has room to grow; on a fixed number of bits, the leftmost bit may be lost.

Exercise 9: Megabits or megabytes: how long does a download take?

7 answers to check

A home internet plan is advertised at 300 Mbps, megabits per second. A game update weighs 45 GB, gigabytes. Internet speeds and download sizes both use the SI prefixes: mega is 10 ** 6, giga is 10 ** 9, and a byte is 8 bits. A student estimates the download time with this program.

Python
SPEED = 300                          # line 1: Mbps
size = 45                            # line 2: GB
seconds = size * 1000 / SPEED        # line 3
print(seconds / 60, 'min')           # line 4
  • a) What does line 4 print?
  • b) At its advertised speed, how many megabytes per second does the connection carry?
  • c) Which line 3 gives the time in seconds? How many minutes does the update really take at 300 Mbps?
  • d) A video call uses 5 Mbps for 2 hours. How many GB of data does it use?
  • e) During the download, the game's launcher shows 30 MB/s. What is that speed in Mbps? What percentage of the advertised speed is it?

Type your answers, the page tells you right or wrong 0/7

a)
b)
c)
d)
e)
Show the solution

Answers

  • a) 2.5 min
  • b) 37.5 MB/s
  • c) seconds = size * 1000 * 8 / SPEED; 20 min
  • d) 4.5 GB
  • e) 240 Mbps; 80 %

A size divided by a speed gives a time once both are in the same unit: megabits with megabits, or megabytes with megabytes. Mbps counts bits, GB counts bytes, and one byte is 8 bits. The table below converts both quantities.

a)

45 × 1000 / 300 = 150 seconds, and 150 / 60 = 2.5: line 4 prints 2.5 min.

45 × 1000 is the size in MB, but 300 is a speed in megabits: the program divides megabytes by megabits per second.

b)

300 megabits per second, divided by 8 bits per byte: 300 / 8 = 37.5 MB per second.

Pitfall: reading Mbps as megabytes per second. The lower-case b is a bit, the capital B a byte.

c)

45 GB = 45000 MB = 45000 × 8 = 360000 megabits: seconds = size * 1000 * 8 / SPEED.

360000 / 300 = 1200 s, that is 1200 / 60 = 20 min, eight times the 2.5 min of the student's program. This is a best case: a real download often runs below the advertised speed.

d)

5 Mbps for 2 h = 7200 s: 5 × 7200 = 36000 megabits.

36000 / 8 = 4500 MB = 4.5 GB.

e)

30 MB/s × 8 = 240 Mbps.

240 / 300 = 0.8, that is 80 % of the advertised speed. At that speed, the update takes 45000 / 30 = 1500 s, that is 25 min.

QuantityGivenConvertedadvertised speed300 Mbps300 / 8 = 37.5 MB/supdate45 GB = 45000 MB45000 × 8 = 360000 Mbtime360000 / 3001200 s = 20 minPut both quantities in the same unit before dividing

Exercise 10: Problem: counting the bytes of a message in UTF-8

9 answers to check

Unicode gives every character of every writing system a number, its code point, written U+ followed by hexadecimal digits. ASCII is the first 128 code points, 0 to 127. In Python, ord(c) gives back the code point of c in decimal, and chr(n) the character of code point n. A chat app sends text in UTF-8, the encoding of most of the Web, which stores one code point on 1 to 4 bytes according to its size, as the first table shows. The second table gives three code points of the test message.

Write a program that reads a message, then displays its number of characters and its number of bytes in UTF-8. Test it on the message Go Zoë! ♪🍁, which has a space after Go and a space after the !.

Code pointBytes0 to 127 (ASCII)1128 to 204722048 to 65535365536 and more4UTF-8: bytes for one code pointCharacterCode pointe with diaeresisU+00EBeighth noteU+266Amaple leaf emojiU+1F341Three characters of the message
  • a) Write the program. What does it display for the test message?
  • b) Convert the three code points U+00EB, U+266A and U+1F341 to decimal.
  • c) How many characters of the test message are outside ASCII?
  • d) A classmate displays len(msg) as the number of bytes. By how many bytes is he wrong on the test message?
  • e) The app sends the text in packets of at most 40 bytes. How many maple leaf emojis fit in one packet? How many ASCII letters?

Type your answers, the page tells you right or wrong 0/9

a)
b)
c)
d)
e)
Show the solution

Answers

  • a) 10 characters, 16 bytes
  • b) 235; 9834; 127809
  • c) 3 characters
  • d) 6 bytes too few
  • e) 10 emojis; 40 letters

A character and a byte are no longer the same thing: len counts characters, and UTF-8 gives each one 1, 2, 3 or 4 bytes according to its code point. The program reads each code point with ord and adds its number of bytes with a cascade of elif, from the smallest bound up. The table below gives each character of the test message.

a)

G, o, the two spaces, Z, o and ! are ASCII, 1 byte each: 7 bytes. ë has the code point 235, from 128 to 2047: 2 bytes. ♪ has 9834, from 2048 to 65535: 3 bytes. 🍁 has 127809, 65536 or more: 4 bytes.

10 characters, 7 + 2 + 3 + 4 = 16 bytes: the program displays 10 characters, 16 bytes. In Python, len(msg.encode('utf-8')) gives the same 16.

b)

U+00EB: E × 16 + B = 14 × 16 + 11 = 235.

U+266A: 2 × 4096 + 6 × 256 + 6 × 16 + 10 = 8192 + 1536 + 96 + 10 = 9834.

U+1F341: 1 × 65536 + 15 × 4096 + 3 × 256 + 4 × 16 + 1 = 65536 + 61440 + 768 + 64 + 1 = 127809. chr(127809) gives back the maple leaf.

c)

A character is outside ASCII when its code point is 128 or more: ë, ♪ and 🍁, that is 3 characters.

d)

len(msg) is 10, the number of characters, while the message takes 16 bytes: he counts 6 bytes too few, one for ë, two for ♪ and three for 🍁.

Pitfall: counting one byte per character. In UTF-8, that holds for ASCII characters only.

e)

One emoji of this range takes 4 bytes: 40 / 4 = 10 emojis. One ASCII letter takes 1 byte: 40 letters.

The same packet holds four times fewer characters when they are emojis, which is why an app limits messages in bytes, not in characters.

Python
msg = input('Message: ')
size = 0
for ch in msg:
    code = ord(ch)
    if code < 128:
        size = size + 1
    elif code < 2048:
        size = size + 2
    elif code < 65536:
        size = size + 3
    else:
        size = size + 4
print(len(msg), 'characters,', size, 'bytes')
CharacterordBytesG711o1111space321Z901o1111e with diaeresis2352!331space321eighth note98343maple leaf127809410 characters, 7 + 2 + 3 + 4 = 16 bytes
Something missing from this set? A type of exercise your teacher gives, a problem you are stuck on, a mistake you spotted: tell me, I read every request.

Sending goes through your free space: that is how I can answer you and tell you when the exercise is added. An email is enough, no password. Create your space. Rather not create an account? Write to me directly.

What is it about?
I read every request myself, nobody else sees it. No need to write your name or your school.
When your request is dealt with, you hear about it by email and in your space.

By sending, you agree that I read your request to answer it. It is kept with your account, erased with it, and never published: privacy policy.

© Ahmed Squalli Houssaini. Exercise set published at www.letuteurscientifique.ca/en/exercices/ics3u-binary-hexadecimal-data-representation. Free for personal and classroom use; republishing it elsewhere requires written permission (legal notice).

Preparing for an ICS3U unit test?

I tutor Grade 11 computer science in English or in French, online. Get in touch for a first session: conversions, codes and units come back on the final exam.

Site by Studio Squalli