A Level Computer Science · Chapter 13 · Component 01: Computer systems
Every number, letter and colour inside a computer is a pattern of bits, and knowing how those patterns work explains overflow, negative numbers and garbled text.
This chapter covers binary and hexadecimal, binary addition and subtraction, negative numbers in two's complement, shifts and masks, and character sets. These are the tools the rest of the course uses whenever it talks about data inside a machine.
In this chapter · jump to a section
Start here
Your route through this chapter
By the end of this chapter you will be able to:
- name the primitive data types and choose a suitable one for a piece of data
- convert between binary, denary and hexadecimal, and explain why hexadecimal is used
- add binary numbers and recognise overflow
- represent negative integers in sign and magnitude and in two's complement, and give their ranges
- subtract in binary using two's complement
- apply logical and arithmetic shifts, and use AND, OR and XOR masks to manipulate bits
- explain ASCII and Unicode, and calculate the storage a piece of text needs
Time: three sessions, about 4 hours, plus the programming task.
You need first: place value in denary, and the idea of a variable from programming.
The big picture
The big picture
On 4 June 1996, the first Ariane 5 rocket left its launch pad in French Guiana. Thirty-seven seconds later it veered off course and broke apart. The cause was a single line of software. A 64-bit value for the rocket's sideways speed was squeezed into a 16-bit integer.
On the older Ariane 4, that speed had always been small enough to fit. Ariane 5 was faster. The value no longer fitted in 16 bits, the conversion failed, and the guidance computer shut down. The rocket and the four satellites it carried, worth several hundred million dollars, were lost.
The lesson is simple and deep. A computer does not store numbers. It stores patterns of bits, and the program decides what each pattern means. If the pattern is too short for the number, or is read in the wrong way, the result can be silently, disastrously wrong.
The same bits can mean different things. The byte 01000001 is 65 if read as an unsigned integer. It is the letter A if read as an ASCII character. It could be part of a colour, an instruction or a sound sample. Nothing in the byte itself says which.
So this chapter is about agreements. Binary place values are an agreement about whole numbers. Two's complement is an agreement about negative numbers. ASCII and Unicode are agreements about characters. Once you know the agreement, you can read any pattern and predict what the hardware will do with it.
Hexadecimal is the programmer's shorthand for long patterns. It packs four bits into a single digit, so a byte is just two characters. You will meet it in colour codes, memory addresses and network addresses.
Arithmetic on bit patterns has rules of its own. Addition carries, just as in denary, but a fixed number of bits means a result can be too big to fit. Subtraction can be done by adding a negative number, which is why two's complement is so useful.
Finally, programs often need to work on single bits. Shifts move bits left or right, multiplying or dividing by powers of two. Masks pick out, set, clear or flip chosen bits. These tricks run everything from graphics to network routing.
Section 1
Data types, binary and hexadecimal
Choosing a type in practice
Real programs make this choice constantly. A game stores a player's score as an integer, because it changes in whole points. It stores the player's position as a real, because movement is smooth. It stores whether the game is paused as a Boolean, and the player's name as a string.
Getting it wrong causes subtle bugs. Storing money as a real can give rounding errors of a fraction of a penny. Storing an age as a string means that "9" sorts after "10", because strings are compared character by character. The type should match what the program will do with the data.
Primitive data types
A primitive data type is one built into a programming language. The common ones are integer, real, Boolean, character and string. Each is stored as bits, and each suits a different kind of data.
An integer holds a whole number, such as a count or an age. A real, or float, holds a number with a fractional part, such as a price or a temperature. A Boolean holds true or false. A character holds one letter, digit or symbol. A string holds a sequence of characters, such as a name.
Choosing the right type matters. An integer is exact and fast. A real can hold fractions but may be slightly inaccurate. A string can hold anything, but arithmetic on it is meaningless. Data that is never calculated with, such as a phone number, is best stored as a string.
Common mistake: storing a phone number as an integer. A phone number is never added or multiplied, and its leading 0 matters. Stored as an integer, 07700 900123 loses its leading 0 and may overflow. Store identifiers like this as strings.
Binary
Binary is base 2. Each place is worth twice the place to its right: 1, 2, 4, 8, 16, 32, 64 and 128 for an 8-bit byte. To convert binary to denary, add the place values of the 1 bits.
To convert denary to binary, work from the largest place value down. If the place value fits into what is left, write 1 and subtract it. Otherwise write 0. Repeat until every place is filled.
Eight bits make a byte, and a byte can hold 2⁸ = 256 different patterns. As unsigned integers, those are 0 to 255. In general, n bits give 2ⁿ patterns, from 0 to 2ⁿ − 1.
Worked example 1: binary to denary and hexadecimal
Convert 10110111 to denary and to hexadecimal.
| Working | Reason |
|---|---|
| 1 bits at 128, 32, 16, 4, 2 and 1 | Read each bit against its place value |
| 128 + 32 + 16 + 4 + 2 + 1 = 183 | Add the place values of the 1 bits |
| Split into nibbles: 1011 and 0111 | One hexadecimal digit holds four bits |
| 1011 = 11 = B and 0111 = 7, so B7 | Hex digits above 9 use the letters A to F |
Why binary?
Computers use binary because their switches have two reliable states. A transistor is either conducting or not, and a voltage is either high or low. Telling two states apart is easy even when the signal is noisy. Telling ten states apart, for denary, would be far less reliable.
Binary also makes the circuits simple. Logic gates work on two values, and a single gate design can be copied millions of times. Every more complicated thing a computer does, from arithmetic to graphics, is built from these two-state switches.
Hexadecimal
Hexadecimal is base 16. It needs sixteen digits, so after 0 to 9 it uses the letters A to F for 10 to 15. Its place values are 1, 16, 256 and so on.
Hexadecimal is popular because 16 = 2⁴. Each hex digit stands for exactly four bits, so converting is just grouping. A byte is always two hex digits, which is far easier to read and type than eight binary digits.
Common mistake: treating hex digits above 9 as two digits. In hexadecimal, 12 is a single digit, written C. Writing it as "12" mixes two digits worth 1 × 16 + 2 = 18. Each hex digit is one symbol from 0 to F.
Worked example 2: denary to binary and hexadecimal
Convert 156 to 8-bit binary and to hexadecimal.
| Working | Reason |
|---|---|
| 156 − 128 = 28, so the 128 bit is 1 | The largest place value that fits |
| 28 − 16 = 12, then 12 − 8 = 4, then 4 − 4 = 0 | Bits 16, 8 and 4 are 1; 64, 32, 2 and 1 are 0 |
| Binary: 10011100 | Write a 1 or 0 for every place |
| Nibbles 1001 and 1100 give 9 and C, so 9C | Converting back to denary gives 156 again |
Bits, bytes and units
Four bits make a nibble, and eight bits make a byte. Larger amounts use prefixes. In storage, a kilobyte is often taken as 1,000 bytes, but in memory it is often 1,024 bytes, which is 2¹⁰. The binary units are named kibibyte, mebibyte and gibibyte to avoid the confusion.
The difference grows with size. A gibibyte is 1,073,741,824 bytes, about 7% more than a gigabyte. That is one reason a new hard drive seems to hold less than its label says when a computer reports its size in binary units.
Converting by repeated division
There is a second way to convert denary to binary. Divide the number by 2, and write down the remainder. Divide the quotient by 2 again, and repeat until the quotient is 0. The remainders, read from last to first, are the binary digits.
For 13: 13 ÷ 2 = 6 remainder 1, 6 ÷ 2 = 3 remainder 0, 3 ÷ 2 = 1 remainder 1, and 1 ÷ 2 = 0 remainder 1. Reading the remainders upwards gives 1101. This method is the one the programming task uses.
Where hexadecimal is used
You meet hex in many places. Web colours are written as six hex digits, such as #FF8800, two for each of red, green and blue. Memory addresses in error messages are hex. MAC addresses of network cards are written as six pairs of hex digits.
In each case, hex is a human-friendly way to write binary. The computer still stores bits. Hex simply makes long patterns shorter and less error-prone for people to read, copy and compare.
Check yourself. Convert the hexadecimal number 3C to binary and to denary.
Show the answer
3 is 0011 and C is 1100, so 3C is 00111100 in binary. In denary that is 3 × 16 + 12 = 60.
Section 2
Binary addition and overflow
The four rules
Binary addition follows four rules. 0 + 0 = 0. 0 + 1 = 1. 1 + 1 = 10, which is 0 carry 1. And 1 + 1 + 1 = 11, which is 1 carry 1. That last rule is needed when a column already has a carry coming in.
Add from the right, column by column, just as in denary. Write the carries above the next column so you do not forget them. Most marks are lost by dropping a carry, not by misunderstanding the method.
Common mistake: dropping the carry in binary addition. In the column 1 + 1 the sum bit is 0, but a carry of 1 must go into the next column. Forgetting it gives an answer that is too small. Write every carry above its column.
Worked example 3: adding two bytes
Add 00010101 and 00001110.
| Working | Reason |
|---|---|
| Right column: 1 + 0 = 1 | No carry is needed yet |
| Next: 0 + 1 = 1; then 1 + 1 = 0 carry 1 | Two 1s give a sum of 0 and a carry |
| Then 0 + 1 + 1 = 0 carry 1, and 1 + 0 + 1 = 0 carry 1 | Each carry is added into the next column |
| Result: 00100011, which is 35 | This matches the denary sum of 21 and 14 |
Checking an addition
A quick check catches most errors. Convert both numbers and the answer to denary, and see whether the sum is right. If the binary answer is wrong, compare column by column to find the dropped carry. In an exam, this check takes seconds and can save several marks.
Another check is the last bit. The sum of two even numbers is even, so its last bit must be 0. The sum of one odd and one even number is odd, so its last bit must be 1. A wrong last bit means the very first column was added wrongly.
Overflow
A byte can hold only 0 to 255 as an unsigned number. If a sum is bigger, the extra bit has nowhere to go. It is carried out of the top column and lost, and the 8 bits left show the wrong value. This is overflow.
Processors detect it. A carry out of the top bit sets a flag in the status register. A program can test that flag and react, for example by reporting an error or switching to a larger type.
Worked example 4: an overflow
Add the unsigned bytes 11001000 and 01010000.
| Working | Reason |
|---|---|
| 11001000 is 200 and 01010000 is 80 | Convert first to know the true total |
| Adding gives 1 00011000 | Nine bits: a carry comes out of the top column |
| Only eight bits are kept: 00011000, which is 24 | The carry out is lost from the byte |
| Overflow: the true total, 280, is above 255 | The processor sets its carry flag |
Common mistake: ignoring overflow. A result that does not fit is not just slightly wrong; it wraps round to a small number. Ariane 5 failed this way. Always check whether the true answer fits in the number of bits available.
Overflow in the real world
Overflow keeps happening, even in famous systems. In 2014 the music video "Gangnam Style" passed 2,147,483,647 views on YouTube, the largest value of a 32-bit signed integer. YouTube had already moved its view counter to 64 bits, so nothing broke, but the counter was close to wrapping round.
A bigger problem is waiting in 2038. Many systems store time as the number of seconds since 1 January 1970 in a 32-bit signed integer. That count overflows in January 2038. Systems still using 32-bit time will jump back to 1901 unless they are updated.
Why fixed width?
Hardware uses a fixed number of bits because registers and memory locations have a fixed size. A 64-bit processor adds 64-bit numbers in one step. Larger numbers need several steps and special code, which some languages, such as Python, do automatically for integers.
Check yourself. Twelve bits are used for an unsigned integer. What is the biggest value they can hold?
Show the answer
Twelve bits give 2¹² = 4096 patterns. The smallest is 0, so the largest is 4096 − 1 = 4095.
Section 3
Negative numbers
Sign and magnitude
The simplest way to store a negative number is to use the first bit as a sign. A 0 means positive and a 1 means negative. The other bits hold the size, or magnitude. So in 8 bits, +5 is 00000101 and −5 is 10000101.
Sign and magnitude is easy to read, but it has two flaws. There are two zeros, 00000000 and 10000000, which wastes a pattern. Worse, ordinary binary addition gives wrong answers, so hardware needs extra circuits to handle signs.
Common mistake: adding sign and magnitude numbers directly. Adding 00000101 (+5) and 10000011 (−3) with normal binary addition gives 10001000, which is −8, not +2. Sign and magnitude needs special rules for arithmetic; two's complement does not.
One's complement
An older method, one's complement, negated a number by flipping every bit, without adding 1. It was used in some early computers. Like sign and magnitude, it has two zeros: 00000000 and 11111111. Adding one's complement numbers needs an extra step, called the end-around carry.
These two flaws, two zeros and awkward addition, are exactly what two's complement removes. Adding 1 after flipping shifts every negative pattern along by one, so the second zero disappears and the arithmetic becomes ordinary binary addition.
Two's complement
Two's complement solves both problems. The first bit is worth minus its usual value: −128 in a byte. The other bits keep their normal positive values. So 11111111 is −128 + 127 = −1, and 10000000 is −128.
There is only one zero, and ordinary binary addition just works. That is why every modern processor uses two's complement for signed integers. The same adder circuit adds signed and unsigned numbers alike.
Forming a negative
To find the two's complement of a negative number, start with the positive number in binary. Flip every bit, then add 1. To check, read the result with the −128 place value; it should give the negative number.
A quick method gives the same answer. Starting from the right, copy bits up to and including the first 1. Then flip every bit to the left of it. For 42 = 00101010, copying 10 and flipping the rest gives 11010110.
Worked example 5: forming −42
Write −42 in 8-bit two's complement.
| Working | Reason |
|---|---|
| +42 = 00101010 | Start from the positive value in binary |
| Flip every bit: 11010101 | Each 0 becomes 1 and each 1 becomes 0 |
| Add 1: 11010110 | Two's complement is flip, then add one |
| Check: −128 + 64 + 16 + 4 + 2 = −42 | The first bit is worth −128 |
Common mistake: flipping the bits but not adding 1. Flipping alone gives one's complement, which is one less than the true negative. 11010101 is −43, not −42. Always add 1 after flipping.
Figure 13.1 shows any value from −127 to 127 in both representations at once. Move through the negative values and compare the patterns. Then switch on the wrong model to see what flipping without adding 1 produces.
Two's complement and sign and magnitude
- Two's complement
- 11010110
- Sign and magnitude
- 10101010
- Read back from two's complement
- −42
Why it works
Two's complement works like a clock. On a clock with 12 hours, going back 1 hour is the same as going forward 11. In 8 bits there are 256 patterns, so subtracting 1 is the same as adding 255, and 255 is the pattern 11111111, which two's complement reads as −1.
Derivation: why flipping and adding 1 negates a number
Flipping every bit of an n-bit pattern x gives a pattern whose bits fill in exactly the 0s of x. Adding the two gives all 1s.
Rearranging, and adding 1 to both sides, gives the flipped pattern plus 1.
In n bits, 2ⁿ is a carry that falls off the top, so 2ⁿ − x behaves exactly like −x. That is why flipping and adding 1 gives the negative, and why the adder needs no special rules.
Range
In n-bit two's complement, the most negative value is −2ⁿ⁻¹ and the largest is 2ⁿ⁻¹ − 1. For 8 bits, that is −128 to 127. There is one more negative number than positive, because zero takes one of the positive-looking patterns.
Common mistake: giving the 8-bit range as −127 to 127. That is the range of sign and magnitude, which wastes a pattern on a second zero. Two's complement has one zero, so its range reaches −128.
Worked example 6: reading two's complement
Find the denary value of 10110011 in 8-bit two's complement.
| Working | Reason |
|---|---|
| The first bit is 1, so the number is negative | The −128 place is set |
| 1 bits at −128, 32, 16, 2 and 1 | Read each bit against its place value |
| −128 + 32 + 16 + 2 + 1 = −77 | Add the place values, including the negative one |
| Result: −77 | Check: flipping and adding 1 gives 01001101 = 77 |
Check yourself. Give the smallest and largest values of a 16-bit two's complement integer.
Show the answer
It is −2¹⁵ to 2¹⁵ − 1, which is −32,768 to 32,767. The most negative value has one more step than the largest positive value.
Section 4
Binary subtraction
Subtracting by adding
Two's complement turns subtraction into addition. To work out A − B, find the two's complement of B, which is −B. Then add it to A. The same adder circuit does the job, so the processor needs no separate subtractor.
When adding, a carry may come out of the top column. In two's complement subtraction, this final carry is discarded. The eight bits left are the correct answer, positive or negative.
Worked example 7: a positive result
Calculate 00110100 − 00011001 using two's complement.
| Working | Reason |
|---|---|
| 00110100 = 52 and 00011001 = 25 | Know the expected answer, 27 |
| −25: flip 00011001 to 11100110, add 1: 11100111 | Form the two's complement of B |
| 00110100 + 11100111 = 1 00011011 | Ordinary binary addition of the two patterns |
| Discard the carry: 00011011, which is 27 | The final carry is ignored in subtraction |
Common mistake: keeping the final carry in two's complement subtraction. The carry out of the top column is not part of the answer. Keeping it gives a nine-bit result such as 100011011, which reads as 283. Discard it and keep eight bits.
A negative result
If the answer is negative, there is usually no carry out, and the result has a 1 as its first bit. Read it with the −128 place value. For example, 20 − 45 gives 11100111, which is −128 + 64 + 32 + 4 + 2 + 1 = −25.
Subtraction in the processor
Inside the processor, subtraction really is addition. The arithmetic logic unit flips the bits of the second number with a row of XOR gates. It sets the first carry in to 1, which adds the 1. Then the usual adder does the rest.
So one control signal switches the whole circuit between adding and subtracting. This is far cheaper than building a separate subtractor, and it is one of the main reasons two's complement won over every other way of storing negative numbers.
Signed overflow
Two's complement can overflow too. Adding two positive numbers whose total is above 127 gives a result with a 1 as its first bit, which reads as negative. Adding two negatives whose total is below −128 gives a positive-looking result.
The rule is easy to check. Overflow has happened if the two numbers have the same sign but the result has the other sign. Numbers with different signs can never overflow when added, because the result is always between them.
Carry and overflow flags
Processors keep two separate flags. The carry flag is set when a carry comes out of the top bit, which signals overflow for unsigned numbers. The overflow flag is set by the sign rule, which signals overflow for two's complement numbers.
The processor does not know whether a program means its numbers to be signed or unsigned. It sets both flags after every addition, and the program checks whichever one matches its own agreement. This is the same idea again: the bits are the same, and the meaning is chosen by the program.
Worked example 8: signed overflow
Add 01101001 and 00111010 as 8-bit two's complement numbers.
| Working | Reason |
|---|---|
| 01101001 = 105 and 00111010 = 58 | Both are positive, with a first bit of 0 |
| Sum: 10100011 | Ordinary binary addition, with no carry out |
| The first bit is 1, so it reads as −93 | Read with the −128 place value |
| Overflow: 105 + 58 = 163 is above 127 | Two positives gave a negative-looking result |
Check yourself. Using two's complement, find the 8-bit pattern for 20 − 45.
Show the answer
45 is 00101101, so −45 is 11010011. Adding 00010100 + 11010011 gives 11100111, with no carry out. Reading it with the −128 place gives −25, as expected.
Section 5
Shifts and masks
Logical shifts
A logical shift moves every bit left or right by a number of places. Bits that fall off the end are lost, and 0s come in on the other side. Shifting left by one place doubles an unsigned number. Shifting right by one place halves it, dropping any remainder.
So a shift left by n places multiplies by 2ⁿ, and a shift right by n places divides by 2ⁿ. Processors shift in a single step, so programmers and compilers use shifts as fast multiplication and division by powers of two.
Worked example 9: shifting
Shift 00010110 left by two places, and shift 10110000 right by three places using a logical shift.
| Working | Reason |
|---|---|
| 00010110 = 22; shift left 2: 01011000 | Two 0s enter on the right |
| 01011000 = 88, which is 22 × 4 | A left shift of 2 multiplies by 2² |
| 10110000 = 176; logical shift right 3: 00010110 | Three 0s enter on the left |
| 00010110 = 22, which is 176 ÷ 8 | A right shift of 3 divides by 2³ |
Lost bits
A shift can lose information. Shifting 00010111 (23) right one place gives 00001011 (11), because the last 1 falls off the end. The result is 23 ÷ 2 rounded down, so the remainder is lost. A shift left can lose a 1 off the top, which is an overflow.
Programs that need the remainder of a division by a power of two use a mask instead. ANDing with 00000001 gives the remainder after dividing by 2, and ANDing with 00000111 gives the remainder after dividing by 8. Shifts and masks together give the quotient and the remainder.
Arithmetic shifts
A logical right shift breaks negative numbers. Shifting 10110000 (−80 in two's complement) right with 0s gives a positive result. An arithmetic right shift copies the sign bit into the gaps instead, so the number keeps its sign.
So 10110000 shifted arithmetically right by three gives 11110110, which is −10. That is −80 ÷ 8, as it should be. A left shift is the same in both kinds, but it can overflow if bits that matter fall off.
Common mistake: using a logical shift on a negative number. A logical right shift fills with 0s, which turns a negative two's complement number positive. To divide a signed number by a power of two, use an arithmetic shift, which copies the sign bit.
Derivation: why a shift left doubles a number
An unsigned n-bit number is the sum of its bits times their place values, with bit i worth 2ⁱ.
A shift left by one place moves each bit up one position, so bit i now has place value 2ⁱ⁺¹.
So every place doubles, and the whole value doubles, as long as no 1 bit falls off the left end. A shift right halves each place in the same way, dropping the bit that falls off the right.
Shifts in compiled code
Compilers use shifts to speed up arithmetic. Multiplying by 8 can be replaced by a shift left of three places, and dividing by 4 by a shift right of two. On older processors, a shift took one clock cycle while a multiplication took many.
Combinations of shifts and additions handle other numbers. Multiplying by 10 is the same as shifting left three places, shifting left one place, and adding the two. That is 8x + 2x, which equals 10x.
Bitwise operators
The bitwise operators AND, OR and XOR combine two patterns one bit at a time. Each bit of the result depends only on the two bits in the same position. NOT flips every bit of a single pattern.
These operators make masks. A mask is a pattern chosen to act on certain bits. The bits where the mask is 1 are the ones changed or kept; the bits where it is 0 are the others.
Three jobs
Each operator does one job with a mask. AND with a mask keeps the bits where the mask is 1 and clears the rest to 0. OR with a mask sets the bits where the mask is 1 and keeps the rest. XOR with a mask flips the bits where the mask is 1 and keeps the rest.
So to test whether bit 2 is set, AND with 00000100: the result is non-zero only if that bit is 1. To set bit 2, OR with 00000100. To clear it, AND with 11111011. To toggle it, XOR with 00000100.
Common mistake: using AND to set bits. AND can only turn bits off, because any 0 in the mask forces a 0. To set bits, use OR, where a 1 in the mask forces a 1. Match the operator to the job before choosing the mask.
Figure 13.2 lets you try each operator on any byte. Choose a value, a mask and an operator, and watch which bits change. Then switch on the wrong model, which uses the opposite operator.
Masks: AND, OR and XOR
- Result
- 00000110 = 6
- In hexadecimal
- 06
- AND mask
- keeps the bits where the mask is 1 and clears the rest
Worked example 10: extracting a field
A byte 10110110 holds two 4-bit fields. Extract the lower field as a number.
| Working | Reason |
|---|---|
| Mask 00001111 selects the lower four bits | 1s mark the bits to keep |
| 10110110 AND 00001111 = 00000110 | Each bit is 1 only where both are 1 |
| The lower field is 0110, which is 6 | The upper bits have been cleared |
| For the upper field: shift right 4, giving 00001011 = 11 | Shifting moves the field into the low bits |
Masks in a program
Most languages provide the bitwise operators directly. In Python they are &, | and ^ for AND, OR and XOR, with ~ for NOT and << and >> for shifts. So flags & 4 tests bit 2, and flags | 4 sets it.
Packing data into bits saves memory and time. Eight Boolean settings fit in one byte instead of eight. Games, operating systems and network software all use this, because it lets one instruction test or change many settings at once.
Uses of masks
Masks appear wherever data is packed into bits. Permissions on a file are bits for read, write and execute. A network address is combined with a subnet mask, using AND, to find the network it belongs to. A colour's red, green and blue values are packed into one number and pulled apart with shifts and masks.
XOR has a special property: applying the same mask twice restores the original. That makes it useful for simple encryption and for toggling settings on and off.
Check yourself. Which mask and operator would clear the top bit of a byte while keeping the other seven bits?
Show the answer
AND with 01111111. The 0 in the top position forces that bit to 0, and the 1s keep the other seven bits as they are.
Section 6
Character sets
Characters as numbers
A character set is an agreed list that gives each character a number, called its code. Text is stored as a sequence of these codes, in binary. When the text is displayed, each code is looked up to find the character to draw.
ASCII was the first widely used standard. It uses 7 bits, giving 128 codes. They cover the English letters in upper and lower case, the digits, punctuation and some control codes, such as the newline.
Patterns in ASCII
The codes are arranged in a useful order. The capital letters run from A = 65 to Z = 90, and the lower case from a = 97 to z = 122. So a character's position in the alphabet is easy to find, and sorting by code sorts alphabetically within each case.
Each lower case letter is exactly 32 more than its capital. In binary that is a single bit, worth 32. So a program can change case by setting or clearing that one bit with a mask, which is how many early programs did it.
The digit characters run from '0' = 48 to '9' = 57. The character '7' is not the number 7. To turn a digit character into its value, subtract 48, the code of '0'.
Common mistake: confusing the character '7' with the number 7. The character '7' is stored as the code 55, not the value 7. Adding the characters '7' and '1' does not give 8. Convert characters to numbers before doing arithmetic with them.
Worked example 11: using character codes
Given that the code for 'A' is 65, find the code for 'D' and for 'd', and the byte 'd' is stored as.
| Working | Reason |
|---|---|
| 'D' is three letters after 'A': 65 + 3 = 68 | Capital letters have consecutive codes |
| 'd' is 32 more than 'D': 68 + 32 = 100 | Lower case is always 32 more than capital |
| 100 = 64 + 32 + 4, so 01100100 | Convert the code to binary |
| The same character with bit 5 cleared is 01000100, 'D' | One bit separates the two cases |
Why 7 bits?
ASCII was designed in the 1960s for teleprinters, when every bit cost money to send. Seven bits were enough for English and the control codes. The eighth bit of a byte was often used as a parity bit, to check for errors in transmission.
Unicode
ASCII has no room for other alphabets, accents or symbols. Extended ASCII used an eighth bit for 128 more characters, but different countries filled them differently. A file written in one could look like nonsense in another.
Unicode solved this by giving every character in every writing system a single code point. It now covers over 150,000 characters, from Latin and Chinese to mathematical symbols and emoji. The first 128 code points are the same as ASCII, so old text still reads correctly.
Common mistake: assuming ASCII can store any character. ASCII has only 128 codes and no letters beyond basic English. A name like "Zoë" or any Chinese, Arabic or emoji text needs Unicode.
Control characters
The first 32 ASCII codes are not printable characters. They are control codes, such as 10 for a new line and 9 for a tab. They told teleprinters and early terminals to move the print head or ring a bell. Some, such as the newline, are still essential today.
Windows and older systems end a line with two control codes, carriage return then line feed. Unix-based systems use the line feed alone. A text file moved between them can show odd symbols or run its lines together, another case of an agreement that differs between systems.
Encodings
Unicode code points must still be stored as bytes. UTF-32 uses four bytes for every character, which is simple but wasteful. UTF-16 uses two bytes for most characters and four for the rest. UTF-8 uses one byte for ASCII characters and up to four for others.
UTF-8 is the most common encoding on the web. English text takes no more space than in ASCII, while any character can still be stored. The word "Café" needs five bytes in UTF-8: one each for C, a and f, and two for é.
When encodings go wrong
When text is saved in one encoding and read in another, it turns into nonsense. Reading UTF-8 bytes as an older 8-bit set turns the é of "café" into two strange symbols, because its two bytes are shown as two separate characters. This garbling is common enough to have a name, mojibake, from the Japanese for "character transformation".
Good programs avoid it by recording the encoding with the text. Web pages declare their encoding in their header. Most modern systems simply use UTF-8 everywhere, which has made mojibake much rarer than it used to be.
Sorting text
Sorting by character code works for plain English in a single case. But codes put every capital before every lower case letter, so "Zebra" sorts before "apple". Accented letters have large codes, so "école" sorts after "zoo".
Real sorting, called collation, follows the rules of each language. A program sorting names should use the language's collation rules rather than raw codes. This is another case where the bits are the same but the agreement about their meaning matters.
Storage calculations
To estimate the storage for text, multiply the number of characters by the bytes per character. A 2,000-character essay in ASCII, at one byte per character, needs 2,000 bytes. The same essay in UTF-32 needs 8,000 bytes.
Check yourself. How many bytes does the text "Hello" need in UTF-32, and why is UTF-8 smaller for it?
Show the answer
UTF-32 uses four bytes per character, so five characters need 20 bytes. UTF-8 stores each ASCII character in a single byte, so "Hello" needs only 5 bytes.
Reference
Key algorithms and definitions
| Term or algorithm | What it means | Example | Cost or rule to learn |
|---|---|---|---|
| Binary | Base 2, place values 1, 2, 4, 8 … | 10110111 = 183 | n bits give 0 to 2ⁿ − 1 unsigned |
| Hexadecimal | Base 16, digits 0 to 9 and A to F | B7 = 183 | One hex digit is four bits |
| Overflow | A result too large for the bits available | 200 + 80 in a byte | Sets the carry or overflow flag |
| Sign and magnitude | First bit is the sign, the rest the size | −5 = 10000101 | Range −127 to 127, two zeros |
| Two's complement | First bit is worth −2ⁿ⁻¹ | −42 = 11010110 | Flip the bits, then add 1 |
| Subtraction | Add the two's complement of the second number | 52 − 25 = 27 | Discard the final carry |
| Logical shift | Move bits, filling with 0s | 22 shifted left 2 is 88 | Left multiplies, right divides by 2ⁿ |
| Arithmetic shift | Right shift that copies the sign bit | −80 shifted right 3 is −10 | Keeps the sign of the number |
| Masks | AND keeps, OR sets, XOR flips | x AND 00001111 | 1s in the mask mark the bits acted on |
| ASCII and Unicode | Codes for characters | 'A' = 65, 'a' = 97 | UTF-8 uses 1 to 4 bytes |
Programming task
Programming task: a base converter
Aim
Write Python functions that convert a whole number to binary, to hexadecimal and to two's complement, and read two's complement back. Test them against the worked examples, including the edges of the range.
Design
To convert to binary, repeatedly divide by 2 and collect the remainders, which give the bits from right to left. Padding with 0s on the left gives the required width. Hexadecimal groups the bits in fours and looks each group up in the string "0123456789ABCDEF".
For two's complement, a negative number n in w bits is stored as the unsigned number 2ʷ + n. Reading it back, a pattern whose first bit is 1 has 2ʷ subtracted. A check rejects values outside the range.
Code
DIGITS = "0123456789ABCDEF"
def to_binary(n, width):
"""Unsigned binary string for n, padded to width bits."""
if n < 0 or n >= 2 ** width:
raise ValueError("does not fit")
bits = ""
while n > 0:
bits = str(n % 2) + bits
n = n // 2
return bits.rjust(width, "0")
def to_hex(n, width):
bits = to_binary(n, width)
return "".join(DIGITS[int(bits[i:i + 4], 2)] for i in range(0, width, 4))
def twos(n, width):
"""Two's complement string for a whole number n."""
if n < -(2 ** (width - 1)) or n > 2 ** (width - 1) - 1:
raise ValueError("out of range")
return to_binary(n + 2 ** width if n < 0 else n, width)
def from_twos(bits):
value = int(bits, 2)
return value - 2 ** len(bits) if bits[0] == "1" else value
print(to_hex(183, 8), twos(-42, 8), from_twos("10110011"))
The loop in to_binary builds the bits from right to left, because each remainder is the next bit up. The check in twos stops a value such as 200 being silently stored as a negative pattern, the same kind of check that Ariane 5 lacked.
Testing
| Test | Input | Expected output | Why this test |
|---|---|---|---|
| 1 | to_binary(156, 8) | 10011100 | Matches worked example 2 |
| 2 | to_hex(183, 8) | B7 | A hex digit above 9 |
| 3 | twos(−42, 8) | 11010110 | Matches worked example 5 |
| 4 | from_twos("10110011") | −77 | Matches worked example 6 |
| 5 | twos(−128, 8) | 10000000 | The most negative value |
| 6 | twos(127, 8) | 01111111 | The largest positive value |
| 7 | twos(128, 8) | ValueError | Just outside the range must be rejected |
Evaluation
The functions agree with every worked example, and the range tests show the boundaries are handled exactly. Test 7 matters most: silently accepting 128 would store it as −128, a hidden overflow.
An improvement would accept a width that is not a multiple of four in to_hex, by padding on the left. Another would add a function that shows the working, printing each division step, as a teaching aid.
Practice
Practice ladder
Rung 1: Recall and fluency
Q1. List the place values of an 8-bit unsigned binary number, from left to right.
Worked solution to Q1
The place values are 128, 64, 32, 16, 8, 4, 2 and 1. Each is double the one to its right, so the leftmost bit is worth 2⁷.
Q2. Give the four rules of binary addition, including the case with a carry in.
Worked solution to Q2
Adding nothing gives nothing: 0 + 0 = 0, and 0 + 1 = 1. Two 1s make two, written 10 in binary, so the column holds 0 and carries 1. With a carry in as well, three 1s make 11, so the column holds 1 and carries 1.
Q3. State which operator and mask would set the lowest bit of a byte, leaving the other bits unchanged.
Worked solution to Q3
Use OR with the mask 00000001. The 1 forces the lowest bit to 1, and the 0s leave the other seven bits exactly as they were.
Rung 2: Application
Q4. Convert 10101101 to denary and to hexadecimal.
Worked solution to Q4
The 1 bits are at 128, 32, 8, 4 and 1, which add to 173. Splitting into nibbles gives 1010 and 1101, which are A and D, so the hexadecimal form is AD.
Q5. Write −77 in 8-bit two's complement and in 8-bit sign and magnitude.
Worked solution to Q5
77 is 01001101. For two's complement, flip the bits to 10110010 and add 1, giving 10110011. For sign and magnitude, set the first bit to 1 and keep the magnitude, giving 11001101.
Q6. Add the unsigned bytes 01011011 and 01001100, and say whether the result overflows.
Worked solution to Q6
Adding column by column gives 10100111, with no carry out of the top bit. As unsigned numbers that is 91 + 76 = 167, which fits below 255, so there is no unsigned overflow.
Q7. Using a mask, extract the upper four bits of 10110110 as a number.
Worked solution to Q7
AND with 11110000 to keep the upper four bits, giving 10110000. Then shift right four places to move them into the low bits: 00001011, which is 11.
Rung 3: Analysis
Q8. Explain whether 01011011 + 01001100 overflows when both are read as 8-bit two's complement numbers.
Worked solution to Q8
Both numbers are positive, 91 and 76, but the result 10100111 has a first bit of 1, so it reads as −89. Two positives giving a negative is signed overflow: the true answer, 167, is above 127.
Q9. Calculate 20 − 45 in 8-bit two's complement, showing each step.
Worked solution to Q9
Form −45: 45 is 00101101, flipped to 11010010, plus 1 gives 11010011. Add 00010100 + 11010011 to get 11100111. There is no carry to discard, and the result reads as −25.
Q10. Apply an arithmetic right shift of one place to 11010000, and explain why a logical shift would be wrong here.
Worked solution to Q10
11010000 is −48. An arithmetic shift copies the sign bit in, giving 11101000, which is −24, exactly half. A logical shift would bring in a 0, giving 01101000, which is +104, so the sign would be lost.
Q11. Calculate the bytes needed to store the text "Café €" in UTF-8 and in UTF-32.
Worked solution to Q11
The text has six characters: C, a, f, é, a space and €. In UTF-8, C, a, f and the space take one byte each, é takes two and € takes three, so 9 bytes. UTF-32 uses four bytes for every character, so 24 bytes.
Rung 4: Stretch
Q12. Show that the range of n-bit two's complement is −2ⁿ⁻¹ to 2ⁿ⁻¹ − 1, using the place values.
Worked solution to Q12
The most negative value has only the first bit set, worth −2ⁿ⁻¹. The largest value has every bit except the first set. Those positive places add to 2ⁿ⁻¹ − 1, one less than the next power of two.
Q13. A program converts a lower case letter to upper case with a single bitwise operation. Give the operator and mask, and show it on 'g', code 103.
Worked solution to Q13
Lower case is 32 more than upper case, so clearing the 32 bit converts it. Use AND with 11011111. The letter 'g' is 01100111, and ANDing gives 01000111, which is 71, the code for 'G'.
Q14. Explain why XOR with the same key, applied twice, restores the original byte. Show it with 10110011 and the key 01011010.
Worked solution to Q14
XOR with a 1 flips a bit, and flipping twice returns it to where it started; XOR with a 0 changes nothing. So 10110011 XOR 01011010 gives 11101001. Applying the key again gives 10110011, the original byte.
Exam practice
Exam technique and worked answer workshop
Conversion questions usually give marks for method and for the answer. Show the place values you used, or the groups of four for hexadecimal. A slip in one bit then costs one mark, not all of them.
For binary arithmetic, write the carries above each column. In subtraction, write the two's complement of the second number on its own line before adding. Then state clearly whether you discarded a final carry and whether overflow occurred.
For masks, name both the operator and the mask, and say what job they do. "AND with 00001111 to keep the lower four bits" earns more than a bare bit pattern. For character questions, show the arithmetic on codes, such as 65 + 3 = 68.
Exam question 1 (4 marks · Paper 01 · about 5 minutes)
(a) Convert the binary number 10101101 to denary. [2]
(b) Convert the same number to hexadecimal, and give one reason why programmers use hexadecimal. [2]
Mark scheme for exam question 1
- M1 place values of the 1 bits identified: 128, 32, 8, 4 and 1
- A1 173
- B1 AD
- B1 hexadecimal is shorter and easier for people to read and copy than binary
Exam question 2 (5 marks · Paper 01 · about 6 minutes)
(a) Add the 8-bit binary numbers 01011011 and 01001100, showing your working. [2]
(b) Both numbers are 8-bit two's complement integers. Explain what the result shows. [3]
Mark scheme for exam question 2
- M1 column addition with carries shown
- A1 10100111
- B1 the two numbers are positive, 91 and 76
- B1 the result has a first bit of 1, so it reads as negative, −89
- B1 this is overflow, because the true total, 167, is above the maximum of 127
Exam question 3 (4 marks · Paper 01 · about 5 minutes)
Represent the denary number −77 in 8-bit binary using:
(a) two's complement [2]
(b) sign and magnitude. [2]
Mark scheme for exam question 3
- M1 +77 written as 01001101
- A1 10110011
- M1 a sign bit of 1 with the magnitude 1001101
- A1 11001101
Exam question 4 (5 marks · Paper 01 · about 7 minutes)
Using 8-bit two's complement, calculate 00010100 − 00101101. Show your working and give the answer in binary and denary.
Mark scheme for exam question 4
- M1 the two's complement of 00101101 formed by flipping and adding 1
- A1 11010011
- M1 00010100 added to 11010011
- A1 11100111
- A1 −25
Exam question 5 (6 marks · Paper 01 · about 9 minutes)
A messaging app will be used by people around the world. Discuss whether it should store messages in ASCII or in Unicode, and which Unicode encoding it should use.
Mark scheme for exam question 5
Level 3 (5–6 marks): a clear comparison of ASCII and Unicode, with the number of characters each can represent. The answer evaluates at least two Unicode encodings for this app and reaches a justified recommendation. Technical terms are used accurately throughout.
Level 2 (3–4 marks): a correct comparison of ASCII and Unicode with some reference to the app. The discussion of encodings is limited, or the recommendation is not fully justified.
Level 1 (1–2 marks): some relevant points, such as that Unicode has more characters, with little application to the app. The answer may lack structure.
0 marks: no response or no response worthy of credit.
Indicative content:
- ASCII uses 7 bits, giving only 128 characters, mainly English letters, digits and punctuation
- users around the world need other alphabets, accents and scripts, which ASCII cannot store
- messages often contain emoji, which need Unicode
- Unicode gives every character in every writing system a code point
- the first 128 Unicode code points match ASCII, so English text is compatible
- UTF-32 uses four bytes per character, which wastes storage and bandwidth
- UTF-8 uses one byte for ASCII and up to four for other characters
- recommendation: Unicode stored as UTF-8, which is compact for most messages and universal
Annotated model answer: exam question 5
"ASCII uses 7 bits, so it has only 128 codes. These cover English letters, digits and punctuation, but no other alphabets or accented letters. An app used worldwide could not store messages in Chinese, Arabic or Hindi, or even names like Zoë." (ASCII's limits, applied to the app.)
"Messaging users also send emoji, which are not in ASCII at all. Unicode gives every character in every writing system its own code point, including emoji, so it can store any message." (Why Unicode is needed.)
"Unicode must be stored in an encoding. UTF-32 uses four bytes per character, so a short English message would take four times the space it needs. UTF-8 uses one byte for each ASCII character and up to four for others." (Two encodings compared.)
"So the app should use Unicode in UTF-8. English messages stay as small as ASCII, messages in other scripts and emoji still work, and UTF-8 is the standard on the web." (A justified recommendation.)
This answer reaches Level 3 and scores 6 marks. It compares, applies each point to the app and makes a clear choice.
Exam question 6 (6 marks · Paper 02 · about 9 minutes)
An 8-bit integer flags stores eight on or off settings, with bit 0 as the least significant bit. Write a function isSet(flags, n) that returns True if bit n is 1. Then write a function setBit(flags, n) that returns flags with bit n set to 1. Use shifts and bitwise operators.
Mark scheme for exam question 6
- B1 a mask for bit n made by shifting 1 left n places
- M1 flags ANDed with the mask in isSet
- A1 True returned when the result is not 0, and False otherwise
- M1 flags ORed with the mask in setBit
- A1 the new value returned from setBit
- B1 both functions take flags and n as parameters and use no loops or string conversion
Annotated model answer: exam question 6
function isSet(flags, n)
mask = 1 << n
return (flags AND mask) != 0
endfunction
function setBit(flags, n)
mask = 1 << n
return flags OR mask
endfunction
Shifting 1 left by n places makes a mask with a single 1 in position n, which earns the first mark. AND keeps only that bit, so the result is non-zero exactly when the bit is set, earning the next two. OR forces that bit to 1 without changing the others, and returning the result earns the last marks.
Exam question 7 (5 marks · Paper 01 · about 7 minutes)
(a) Apply a logical shift left of two places to 00110100, and state the effect on its value. [2]
(b) Apply a logical shift right of two places to 00110100. [1]
(c) The pattern 11010000 is an 8-bit two's complement number. Apply an arithmetic shift right of one place, and give the denary values before and after. [2]
Mark scheme for exam question 7
- B1 11010000
- B1 the value is multiplied by 4, from 52 to 208
- B1 00001101
- B1 11101000
- B1 −48 before and −24 after
Exam question 8 (5 marks · Paper 01 · about 7 minutes)
(a) State the range of integers that can be stored in 8-bit two's complement. [2]
(b) The ASCII code for 'a' is 97. State the ASCII code for 'd'. [1]
(c) A program reads the character '7' from the keyboard. Explain how it can find the number 7 from the character's code. [2]
Mark scheme for exam question 8
- B1 most negative value −128
- B1 largest value 127
- B1 100
- B1 the character '7' is stored as its code, 55, not the number 7
- B1 subtract 48, the code for '0', to get 7
Connections
Synoptic link
These representations run through the whole course. The adders that perform binary addition are built from gates in Boolean algebra and logic circuits. The carry and overflow flags sit in the processor described in Processor architecture and performance. Floating point numbers extends two's complement to real numbers.
Masks with AND reappear in Networks, protocols and the internet, where a subnet mask picks out the network part of an IP address. Character codes matter in Compression, encryption and hashing, where text is turned into numbers before it is compressed or encrypted.
Synoptic question 1. A device has the IP address 192.168.5.130 and the subnet mask 255.255.255.192. Use AND on the last byte to find the last byte of the network address.
Answer to synoptic question 1
The last byte of the address is 130 = 10000010, and the last byte of the mask is 192 = 11000000. ANDing gives 10000000, which is 128. So the network address ends in 128.
Recap
Recap and next step
- Primitive data types are integer, real, Boolean, character and string; n bits give 2ⁿ patterns.
- Hexadecimal digits stand for four bits each, so conversions are done by grouping.
- Binary addition carries like denary; a result too big for the bits available overflows.
- Two's complement gives the first bit a weight of −2ⁿ⁻¹; to negate, flip the bits and add 1, and the 8-bit range is −128 to 127.
- Subtract by adding the two's complement and discarding the final carry; overflow occurs when two numbers of one sign give the other sign.
- Shifts multiply and divide by powers of two, arithmetic right shifts keep the sign, and AND, OR and XOR masks keep, set and flip bits.
- ASCII gives 128 characters; Unicode covers every script, and UTF-8 stores ASCII in one byte and others in up to four.
Next chapter: Floating point numbers uses two's complement for a mantissa and an exponent to store real numbers.
For your exam board
OCR A Level Computer Science (H446): this chapter covers section 1.4.1, Data types, in Component 01, Computer systems: primitive data types, binary and hexadecimal, sign and magnitude and two's complement, binary addition and subtraction, bitwise manipulation, shifts and masks, and ASCII and Unicode.
AQA A Level Computer Science (7517): number bases, unsigned and signed binary, binary arithmetic, character coding with ASCII and Unicode, and bit manipulation appear in the fundamentals of data representation section, assessed on Paper 2.