Multiplexers, Encoders and Decoders

A computer is full of places where several signals could go down the same wire, but only one of them should go at a time. The circuit that makes that choice is a multiplexer (a mux). The opposite job, spreading one compact code out onto many wires, is done by a decoder, and packing many wires back into a short code is done by an encoder.

In this lesson you will build those three blocks from the AND, OR and NOT gates you already know, watch the live wires change colour as you toggle the inputs, and see how a mux can stand in for a whole truth table. The same rules are then written in C, so you can check a 2-to-1 mux, a 4-to-1 mux and a 2-to-4 decoder on a computer.

What you will learn

  • What a multiplexer does, how the select lines choose a data input, and the 2n rule that links the number of select lines to the number of data inputs.
  • How to draw a 2-to-1 mux as a labelled block, and how to build it from AND, OR and NOT gates.
  • How a 4-to-1 mux is built, including a version made from 2-to-1 muxes, and how to trace Y for a given S1 S0.
  • What a decoder and an encoder do, including a priority encoder when two inputs are 1 at once.
  • How to implement any 2-input truth table by tying the data pins of a 4-to-1 mux to 0 or 1.
  • How a counter wired to the select lines of a mux steps through the data inputs, which is the idea behind some exam questions.
  • How the same rules are written as short C functions.

Part 1: The multiplexer

Think of a mux as a digitally controlled switch. It has several data inputs (I0, I1, …), a smaller group of select lines (S, or S1 and S0, and so on), and a single output Y. The select lines form a binary number. That number is the index of the data input that is copied to Y. All the other data inputs are ignored for as long as the select bits stay the same.

The counting rule is simple and worth memorising: n select lines can choose among 2n data inputs. So a 2-to-1 mux needs one select line, a 4-to-1 mux needs two, an 8-to-1 mux needs three, and a 16-to-1 mux needs four. If a question gives you the number of data inputs, take the power of two; if it gives you the number of select lines, raise two to that power.

A labelled 2-to-1 block

Exam questions often ask you to draw a mux as a labelled block rather than as a nest of gates. Draw a trapezium or a rectangle, put I0 and I1 into one side, put S on a third side, put Y out of the opposite side, and name every arrow. Marks are lost more often for a missing label than for a slightly messy shape. Here is the standard 2-to-1 block, with every pin named:

2-to-1 MUX I0 I1 S Y

A 2-to-1 multiplexer drawn as a labelled block. I0 is the input chosen when S = 0; I1 is chosen when S = 1.

Worked example 1: the 2-to-1 truth table

For a 2-to-1 mux the Boolean expression is:

Y = (NOT S · I0) + (S · I1)

Read that in words: when S is 0, the first AND gate is enabled (because NOT S is 1) and Y copies I0; when S is 1, the second AND gate is enabled and Y copies I1. The two AND outputs are merged by an OR gate, but only one of them is 1 at a time, because S and NOT S cannot both be 1.

Work through one row slowly. Suppose S = 0, I0 = 1 and I1 = 0.

  1. NOT S = NOT 0 = 1.
  2. The top AND computes NOT S · I0 = 1 · 1 = 1.
  3. The bottom AND computes S · I1 = 0 · 0 = 0.
  4. The OR of those two results is 1 + 0 = 1, so Y = 1, which is a copy of I0.

Now flip only the select bit: S = 1, I0 = 1, I1 = 0. NOT S is now 0, so the top AND is forced to 0. The bottom AND is 1 · 0 = 0. The OR is 0, so Y = 0, a copy of I1. The data inputs did not change; only the selected path changed. That is the whole point of a mux.

SI0I1Y
0000
0010
0101
0111
1000
1011
1100
1111

Look down the Y column and check it against the rule: the first four rows, where S = 0, copy the I0 column; the last four rows, where S = 1, copy the I1 column.

A 4-to-1 mux, and two ways to build it

A 4-to-1 mux has data inputs I0, I1, I2 and I3, and two select lines S1 (the more significant bit) and S0 (the less significant bit). Read S1 S0 as a two-bit number: 00 selects I0, 01 selects I1, 10 selects I2 and 11 selects I3. Always treat I0 as the input chosen when the select bits are 00.

One way to build it is with four AND gates and one OR gate. Each AND gate has three inputs: one data bit, and a unique combination of S1, S0, NOT S1 and NOT S0 that is 1 for only one of the four select codes. The four AND outputs go into a four-input OR, and that OR is Y. This is the same idea as a decoder (Part 2) feeding a row of AND gates.

A neater construction uses three 2-to-1 muxes. The first mux, selected by S0, chooses between I0 and I1. The second mux, also selected by S0, chooses between I2 and I3. The third mux, selected by S1, chooses between those two results. You will see exactly this nesting in the C program later: a 4-to-1 mux written as mux2 calls inside mux2. Both constructions give the same Y; the nested version is often easier to draw once you already trust the 2-to-1 block.

Worked example 2: tracing a 4-to-1 mux

Let I0 I1 I2 I3 = 1 0 1 1, and let S1 S0 = 10. First convert the select bits: 10 is the number 2, so the mux must copy I2. I2 is 1, so Y should be 1. Now check it at gate level. NOT S1 = 0 and NOT S0 = 1. The enable line that needs S1 = 1 and S0 = 0 is the enable for I2; that line is 1. The I2 AND gate therefore outputs 1 · 1 = 1. The other three AND gates are disabled, so they output 0. The OR of 0, 0, 1 and 0 is 1. Y is 1, as required.

If the same data is kept and you only change S1 S0 to 01, the index becomes 1, the I1 AND gate opens, I1 is 0, and Y becomes 0. Practise this trace until you no longer have to guess.

Use the live circuit below to confirm both worked examples, then try values of your own. Start in Block view to see which input is routed to Y, then switch to Gate view to trace the AND, OR and NOT gates. Orange wires are at 1; grey wires are at 0, and the selected path is drawn thicker.

Try it 1Multiplexer: block and gate view

Choose Block view or Gate view, pick 2-to-1 or 4-to-1, then tap the select bits and data inputs. Wires light orange when they carry 1, and the selected path is drawn thicker.

Part 2: Decoders and encoders

A decoder takes a compact binary code and turns it into a one-hot pattern: exactly one of its output lines is 1, and the rest are 0. A 2-to-4 decoder has two inputs, A1 and A0, and four outputs Y0, Y1, Y2 and Y3. When A1 A0 = 00, only Y0 is 1; when A1 A0 = 10, only Y2 is 1, and so on. The input is being read as a number, and the output line with that number is raised.

This is how a processor can enable one memory location, or one register, given its address. The address is a short binary number; the decoder raises a single enable line for the chosen cell and leaves the others off, so only that cell is written or read.

Inside, a 2-to-4 decoder is four AND gates and two NOT gates. Each AND gate gets a unique mix of A1, A0, NOT A1 and NOT A0, just as each AND gate of a 4-to-1 mux got a unique mix of the select bits. In fact, the enable lines of a 4-to-1 mux are a decoder. Once you see that, the two circuits start to look like parts of the same idea.

Worked example 3: a 2-to-4 decoder

Let A1 A0 = 10. That is the number 2, so Y2 must be 1 and Y0, Y1 and Y3 must be 0. At the gates: NOT A1 = 0, NOT A0 = 1. The AND gate for Y2 is the one that wants A1 = 1 and A0 = 0; those values are present, so Y2 = 1. The AND gate for Y0 wants NOT A1 and NOT A0; NOT A1 is 0, so Y0 = 0. Y1 wants NOT A1 and A0: NOT A1 is again 0, so Y1 = 0. Y3 wants A1 and A0: A0 is 0, so Y3 = 0. Only one line is high.

An encoder does the reverse. A 4-to-2 encoder looks at four one-hot inputs I0 to I3 and writes the binary number of the line that is 1. If I2 is 1 and the others are 0, the output A1 A0 is 10. You can build A1 with an OR of I2 and I3 (the inputs whose number has a 1 in the 2s place) and A0 with an OR of I1 and I3 (the odd numbers).

A plain encoder is only well-defined when exactly one input is 1. If two inputs are 1 at once, the OR gates mix their codes and the output is no longer a clean number. A priority encoder solves this by picking the highest-numbered input that is 1 and ignoring the others. If I1 and I3 are both 1, a 4-to-2 priority encoder outputs 11 (the code for I3), not 01. Priority encoders turn up in processors when more than one device asks for attention at the same time: the one with the higher priority wins.

Worked example 4: encoder and priority encoder

First the ordinary case. I0 I1 I2 I3 = 0 0 1 0, so only I2 is high. I2 is the number 2, which is 10 in binary, so A1 = 1 and A0 = 0. Check the OR gates: A1 = I2 OR I3 = 1 OR 0 = 1; A0 = I1 OR I3 = 0 OR 0 = 0. Agreed.

Now let I0 I1 I2 I3 = 0 1 0 1, so I1 and I3 are both 1. A plain encoder would compute A1 = 0 OR 1 = 1 and A0 = 1 OR 1 = 1, which happens to be the code for I3, but only because I3 includes both bits. If the two highs had been I1 and I2, a plain encoder would output A1 = 1 and A0 = 1, which is not the code of either input — the result is meaningless. A priority encoder looks from I3 downwards, finds I3 already at 1, and outputs 11, ignoring I1. That is a defined, repeatable answer, which is why exam questions that allow more than one active input are almost always about priority encoders.

Use the live circuit to try all three modes. In decoder mode, tap A1 and A0 and watch a single Y line light up. In encoder mode, tap one I input at a time (the widget keeps the inputs one-hot, which is the honest way to use a plain encoder). In priority mode you can raise several inputs at once and see the highest one win.

Try it 2Decoder, encoder and priority encoder

Switch between Block view and Gate view, choose Decoder, Encoder or Priority encoder, then tap the inputs. Orange wires carry 1.

Part 3: A mux as a truth-table builder, and a mux driven by a counter

Here is a trick that makes muxes even more useful. Tie each data input of a 4-to-1 mux to a constant 0 or a constant 1, and treat the two select lines as the variables A and B of a 2-input function. The four data pins are then exactly the four rows of a truth table, in the order 00, 01, 10, 11. Whatever pattern you tie onto I0 I1 I2 I3 appears, row by row, as Y.

That means you can implement any 2-input Boolean function with one 4-to-1 mux and a handful of fixed 0s and 1s, without building a custom nest of gates for each function.

Worked example 5: XOR from a 4-to-1 mux

XOR is 1 when its two inputs are different. Its truth table for AB = 00, 01, 10, 11 is 0, 1, 1, 0. Tie I0 = 0, I1 = 1, I2 = 1 and I3 = 0, and let S1 be A and S0 be B. When AB = 10, the mux selects I2, which is 1, and Y is 1, which is what XOR should give for 10. When AB = 00, it selects I0 = 0; when AB = 11, it selects I3 = 0. The four pins are the XOR column. NAND would be 1, 1, 1, 0; AND would be 0, 0, 0, 1. Try those patterns in the widget below and watch the truth table fill in.

Worked example 6: a counter on the select lines

In D and JK Flip-Flops, Registers and Counters you built a 2-bit ripple counter that counts 00, 01, 10, 11 and then wraps. Wire that counter to the select lines of a 4-to-1 mux, and as the count ticks, Y will step through I0, I1, I2 and I3 in order. If the data pins hold 1 0 1 0, the output Y is the repeating pattern 1, 0, 1, 0 — a simple way to generate a chosen sequence from a counter. Later exam questions sometimes combine a mux with a counter in exactly this way: first write down the count at each step, then read off Y from the data pin that the count selects.

In the builder below, tap a data pin to tie it to 0 or 1, and tap a row (or a named preset) to choose the current select code. The selected path through the mux block lights up, and the truth table highlights the matching row. If the pin pattern is a named gate such as XOR or NAND, the caption will say so.

Try it 3Mux as a truth-table builder

Tie each data pin of a 4-to-1 mux to 0 or 1. The two select bits are the inputs A and B of a 2-input function. Tap a row to choose S1 S0, or start from a named gate. The selected path through the mux lights up, and the truth table highlights that row.

Part 4: These blocks in C

Hardware and C are saying the same thing, just in a different language. A 2-to-1 mux is an if on the select bit; a 4-to-1 mux can be written as two such choices nested together, which is the same construction as the three 2-to-1 muxes on paper. The decoder loop below raises exactly one of four variables, the way the live circuit raises exactly one Y line. Run the programs, then change a data pin or an address and compile them again, to confirm the traces you have already done by hand.

The first program prints a 2-to-1 mux for one pair of inputs, then a 4-to-1 mux whose data is 0, 1, 1, 0, for every value of S1 S0. Check the 4-to-1 table against the 2n index rule: when S1 S0 is 10 the index is 2, so Y should be the third data bit, which is 1.

#include <stdio.h>

/* A 2-to-1 multiplexer, then a 4-to-1
   built by selecting with two bits. */
int mux2(int s, int i0, int i1)
{
    if (s == 0)
        return i0;
    return i1;
}

int main(void)
{
    int s1, s0, i[4] = {0, 1, 1, 0};
    int y;

    printf("2-to-1: S I0 I1 | Y\n");
    printf("        0  0  1 | %d\n",
           mux2(0, 0, 1));
    printf("        1  0  1 | %d\n",
           mux2(1, 0, 1));

    printf("4-to-1, I = 0 1 1 0\n");
    printf("S1 S0 | Y\n");
    for (s1 = 0; s1 <= 1; s1++)
        for (s0 = 0; s0 <= 1; s0++) {
            y = mux2(s1,
                     mux2(s0, i[0], i[1]),
                     mux2(s0, i[2], i[3]));
            printf(" %d  %d | %d\n",
                   s1, s0, y);
        }
    return 0;
}

Output:

2-to-1: S I0 I1 | Y
        0  0  1 | 0
        1  0  1 | 1
4-to-1, I = 0 1 1 0
S1 S0 | Y
 0  0 | 0
 0  1 | 1
 1  0 | 1
 1  1 | 0

The second program is a 2-to-4 decoder. For each address 0 to 3 it writes A1 A0 and then the four outputs Y3 Y2 Y1 Y0, with a single 1 in the column whose number is the address. (The printout lists Y3 first, which is a common way to write a one-hot pattern from the high line down to Y0.)

#include <stdio.h>

/* A 2-to-4 decoder: one of four lines
   is 1, chosen by A1 A0. */
int main(void)
{
    int a1, a0, n, y0, y1, y2, y3;

    printf("A1 A0 | Y3 Y2 Y1 Y0\n");
    for (n = 0; n < 4; n++) {
        a1 = n / 2;
        a0 = n % 2;
        y0 = (n == 0);
        y1 = (n == 1);
        y2 = (n == 2);
        y3 = (n == 3);
        printf(" %d  %d |", a1, a0);
        printf("  %d  %d", y3, y2);
        printf("  %d  %d\n", y1, y0);
    }
    return 0;
}

Output:

A1 A0 | Y3 Y2 Y1 Y0
 0  0 |  0  0  0  1
 0  1 |  0  0  1  0
 1  0 |  0  1  0  0
 1  1 |  1  0  0  0

Try it 4Mux, decoder and encoder drill

Selection-line questions use the 2n rule. For a 4-to-1 mux, treat S1 S0 as a binary number. Encoder questions assume exactly one input is high.

Summary

  • A multiplexer copies one of several data inputs to a single output. The select lines form the index of the chosen input. n select lines choose among 2n data inputs.
  • A 2-to-1 mux is Y = (NOT S · I0) + (S · I1). A 4-to-1 mux can be built from four AND gates and an OR, or from three 2-to-1 muxes.
  • A decoder turns a compact address into a one-hot set of enable lines. An encoder does the reverse. A priority encoder picks the highest active input when more than one is 1.
  • Tying the data pins of a 4-to-1 mux to 0 or 1 implements any 2-input truth table. Wiring a counter to the select lines steps Y through those pins in order.
  • The same rules can be written in C and checked against a hand trace.

Practice questions

1. Write the Boolean expression for a 2-to-1 mux and evaluate it for S = 1, I0 = 0, I1 = 1.

Show answer

Y = (NOT S · I0) + (S · I1) = (0 · 0) + (1 · 1) = 1.

2. How many select lines does an 8-to-1 multiplexer need? How many data inputs does a mux with 4 select lines have?

Show answer

8 = 23, so 3 select lines. 4 select lines choose among 24 = 16 data inputs.

3. A 4-to-1 mux has I0 I1 I2 I3 = 1 0 1 1 and S1 S0 = 10. What is Y? Trace the enable lines as well as the index.

Show answer

S1 S0 = 10 is the index 2, so Y = I2 = 1. The enable for I2 (S1 = 1 and S0 = 0) is the only enable that is high, so only that AND gate can pass a 1 to the OR.

4. A 2-to-4 decoder has inputs A1 A0 = 01. Which output is 1, and why are the others 0?

Show answer

01 is the number 1, so Y1 is 1. Each other AND gate needs a different mix of A1, A0 and their complements, so Y0, Y2 and Y3 stay 0.

5. A 4-to-2 encoder has I1 = 1 and the other inputs 0. What is A1 A0? How is each bit made from OR gates?

Show answer

I1 is the number 1, so A1 A0 = 01. A1 is I2 OR I3 = 0. A0 is I1 OR I3 = 1.

6. I1 and I3 are both 1 on a 4-to-2 priority encoder. What is the output, and why would a plain encoder be a poor choice if the highs were I1 and I2 instead?

Show answer

The highest 1 is I3, so the priority encoder outputs 11. A plain encoder with I1 and I2 both high would OR the bits together to give 11, which is not the code of either input, so the answer would be meaningless.

7. Show how to make XOR with a 4-to-1 mux. What values do you tie to I0 I1 I2 I3, and which select bits are the variables A and B?

Show answer

Tie I0 I1 I2 I3 = 0 1 1 0. Let S1 be A and S0 be B. Those four pins are the XOR column for AB = 00, 01, 10, 11.

8. A 2-bit counter, starting at 00, is wired to the select lines of a 4-to-1 mux whose data pins are 1 1 0 1. List Y for four successive counts, then the next count after it wraps.

Show answer

Counts 00, 01, 10, 11, 00 give Y = I0, I1, I2, I3, I0 = 1, 1, 0, 1, and then 1 again.

Homework

  • On paper, draw a 2-to-1 mux as a labelled block (every pin named) and also as an AND–OR–NOT circuit. Pick values for S, I0 and I1 and write 1 or 0 on every wire.
  • Build a 4-to-1 mux from three 2-to-1 muxes on paper. Choose S1 S0 = 10 and I0 I1 I2 I3 = 0 1 1 0, and write the output of each of the three muxes.
  • Change mux.c so the 4-to-1 data is 1, 0, 1, 1 and confirm the printed table against Practice question 3.
  • Using the truth-table builder, find a pin pattern that implements NOR, write it down, and explain in one sentence why I0 is 1 and the other three pins are 0.

Mastery quiz: Multiplexers, Encoders and Decoders

This 10-question quiz is separate from the short Quick quiz at the end of the lesson. Score 8/10 or higher to earn this lesson’s badge. Your best score is saved in this browser on this device.

Mastery quiz: Multiplexers, Encoders and Decoders

Your course badges: loading saved progress…

View badges

    No course badges earned yet. Score 8/10 in a lesson quiz to earn its badge.

    Saved in this browser on this device. Clearing browser data may remove your badges.

    Answer all 10 questions. Earn this lesson’s badge at 8/10 or higher. Read the explanations, revisit the Try it activities and retry as often as you need. These are self-study badges, not formal grades.

    1. What is the job of a multiplexer?
    2. A 16-to-1 multiplexer needs how many select lines?
    3. In a 2-to-1 mux, which input is copied to Y when S = 0?
    4. A 4-to-1 mux has I0 I1 I2 I3 = 0 1 0 1 and S1 S0 = 11. What is Y?
    5. Which Boolean expression is correct for a 2-to-1 mux?
    6. A 2-to-4 decoder with inputs 10 has which output equal to 1?
    7. Why does a processor use a decoder on a register address?
    8. A 4-to-2 encoder has I2 = 1 and the other inputs 0. What is A1 A0?
    9. I0 and I3 are both 1 on a 4-to-2 priority encoder. What does it output?
    10. To implement AND with a 4-to-1 mux, which values do you tie to I0 I1 I2 I3?

    Exam tips

    Specimen Unit 1 Paper 02 (2021), Question 1(a). Asks you to draw a 2-to-1 multiplexer as a labelled block, with every input and the output named. Draw the two data inputs, the select line and the output, and name each one. Marks are lost for a missing label more often than for a messy box.

    2009 Unit 1 Paper 02, Question 1. Includes a 4-to-1 multiplexer as part of a longer question on the building blocks. Know how S1 S0 pick the input. Worked solution: 2009 U1 Q1.

    2024 Unit 1 Paper 02, Question 2. Later parts combine a multiplexer with a counter on the select lines, which is exactly Part 3 of this lesson. Trace the count first, then read off Y at each step. Worked solution: 2024 U1 Q2.

    Paper 01 also uses short items of the form "how many select lines does this mux have?" Use the 2n rule and you are done. General advice: always label I0 as the input chosen when the select bits are 00, and always write the select bits as a binary number before you pick an input. More worked answers are on the CS Solutions page.

    Previous: D and JK Flip-Flops, Registers and Counters. Next: The Processor: CPU Components and the Fetch-Decode-Execute Cycle. See also: Multiplexers and Logic Gates and Truth Tables.

    Syllabus link: CAPE Computer Science (CXC A19/U2/21), Unit 1, Module 1: Computer Architecture. Specific Objective 2: describe the basic building blocks of a computer (multiplexors, encoders, decoders).

    Video search terms

    Search YouTube for: "2 to 1 multiplexer explained", "4 to 1 mux from 2 to 1", "2 to 4 decoder truth table", "priority encoder explained", "encoder vs decoder vs multiplexer".

    Try it 5Quick quiz

    Tap an answer. All eight questions are self-checks on this lesson.

    Updates

    2026/11/24

    - Added a block view and a cleaner gate view to the circuit Try its.

    - Tidied the gate labels in the circuit Try its.

    - Rebuilt the lesson with fuller explanations, diagrams and new Try it simulations.

    2026/11/23

    - Removed the Print this lesson button.

    - Reworded some sentences so they speak directly to students.

    - Published.

    © 2026 Vedesh Kungebeharry. All rights reserved.

    D and JK Flip-Flops, Registers and Counters

    The SR Latch remembers one bit, but its outputs follow the inputs for as long as S or R is held. Real computers need a bit that changes only at a chosen instant, so that many bits can be updated together. That instant is the edge of a clock pulse. In this lesson you will meet the two clocked flip-flops named in the CAPE syllabus, the D (Data) flip-flop and the JK flip-flop, see how a row of them makes a register, and build a 2-bit ripple counter that counts 00, 01, 10, 11, 00 on every falling clock edge.

    What you will learn

    • The difference between a latch (level-sensitive) and a flip-flop (edge-triggered).
    • How a D flip-flop copies D to Q on a clock edge and holds it otherwise.
    • The four JK actions: hold, reset, set and toggle, and how J = K = 1 makes a toggle (T) flip-flop.
    • How n flip-flops with a shared clock make an n-bit register.
    • How two toggle flip-flops, with Q0 clocking the second one, make a 2-bit ripple counter that counts on the negative edge.
    • How to model a register and a ripple counter in C.

    Part 1: From a latch to a clocked flip-flop

    A latch is level-sensitive: while the inputs are active, the output can change at any moment. That is awkward when you want a whole word of bits to update together. A flip-flop is edge-triggered: it looks at its inputs only at the moment the clock changes, and holds its value the rest of the time.

    • A rising (positive) edge is the change from 0 to 1.
    • A falling (negative) edge is the change from 1 to 0.

    A flip-flop can be built to use either edge. The widgets in this lesson all use the falling (negative) edge, because that is how the ripple counter in Part 5 is wired. In a question, read the triangle on the clock input: a small bubble (inverting circle) on the clock means negative-edge triggered; no bubble means positive-edge triggered.

    Part 2: The D (Data) flip-flop

    The D flip-flop has one data input D and a clock. On the triggering edge it copies D into Q, and Q′ becomes the opposite. Between edges it holds, whatever D does. In symbols, the next state is simply Q+ = D. That single rule is why the D flip-flop is the usual building block of registers: there is no forbidden input, and you just present the bit you want to store and tick the clock.

    D at the falling edgeQ becomesName
    00Store a 0 (reset)
    11Store a 1 (set)

    Try it 1D flip-flop (falling edge)

    Set D, then tap CLK to raise and lower the clock. Q takes the value of D only when CLK falls from 1 to 0.

    Q
    Q′

      Part 3: The JK flip-flop

      The JK flip-flop has two inputs, J and K, plus a clock. It is the most general of the simple flip-flops: with the right combination of J and K it can hold, reset, set or toggle. The four actions (applied on the triggering edge) are:

      JKAction on the falling edgeNext Q
      00Hold (no change)Q
      01Reset0
      10Set1
      11Toggle (flip Q)NOT Q

      Compare this with the SR latch: J is like S and K is like R, but J = K = 1 is no longer forbidden — it is the most useful case. A JK flip-flop with J and K both tied to 1 (or a single T input held at 1) is called a T (toggle) flip-flop. It flips on every triggering edge, and that is exactly what a binary counter needs.

      Try it 2JK flip-flop (falling edge)

      Choose J and K, then raise and lower CLK. The action is carried out only on the falling edge.

      Q

        Part 4: Registers

        A register is a group of flip-flops that share the same clock, one flip-flop per bit. An 8-bit register is eight D flip-flops side by side: when the clock edge arrives, each flip-flop stores its own D input, so the whole word is loaded at once. The CPU registers you will meet in The Processor: CPU Components and the Fetch-Decode-Execute Cycle (the program counter, the accumulator, the instruction register and so on) are built this way. Because they sit inside the processor they are the fastest storage a computer has; see Memory Types and Features.

        If the D input of each flip-flop is taken from the Q of its neighbour, the same register becomes a shift register: on each clock edge every bit moves one place to the left or right. Shift registers are used in serial communication and in some arithmetic circuits. For CAPE, the important picture is: flip-flops plus a common clock = a register; n flip-flops store n bits.

        Part 5: A 2-bit ripple counter

        A counter is a register wired so that its bit pattern steps through a fixed sequence, usually the binary numbers. The simplest is the ripple (asynchronous) counter. For two bits:

        • Both flip-flops are toggles: J and K are tied to 1, so each one flips when it sees a falling edge on its own clock.
        • The external clock goes only to FF0, the least significant bit (Q0).
        • Q0 is wired to the clock input of FF1, the most significant bit (Q1).

        Follow one cycle, starting at Q1 Q0 = 00, and remember that a flip-flop only changes when its clock falls:

        Falling edge of CLKQ0 (FF0)Does Q0 fall?Q1 (FF1)Count
        1st0 → 1No (it rose)0 (holds)01 = 1
        2nd1 → 0Yes0 → 110 = 2
        3rd0 → 1No1 (holds)11 = 3
        4th1 → 0Yes1 → 000 = 0

        It is called a ripple counter because a change has to work its way, or ripple, along the chain: FF1 cannot toggle until Q0 has already fallen. In real hardware that ripple takes a little time, so a 16-bit ripple counter is slower than a synchronous counter, in which every flip-flop shares the same clock and the toggling is decided by combinational logic. For two bits the delay is tiny, and CAPE mainly asks you to trace the falling-edge behaviour above. (An older animation of the same idea is The Ripple Counter Explained (Animation).)

        Try it 32-bit ripple counter (negative edge)

        Both flip-flops are JK toggles (J = K = 1). The clock goes to FF0; Q0 is the clock for FF1. Tap the clock to raise and lower it, or tap Pulse once for a full high-then-low tick. Outputs change only on the falling edge, which is highlighted, and a timing diagram builds as you go.

        CLK 0 FF0 LSB (J = K = 1) J = 1 K = 1 Q Q′ 0 1 Q0 FF1 MSB (J = K = 1) J = 1 K = 1 Q Q′ 0 1 Q1

        Count

        Clock low (hold)

        Timing diagram. Yellow columns mark a falling edge of CLK, where the count changes.

        Part 6: Flip-flops, registers and counters in C

        C does not have a flip-flop type, but the rules are ordinary assignment. The program below is the 2-bit ripple counter from Part 5. A loop flips a clk variable eight times (four complete pulses). The outputs change only in the branch that sees a falling edge, and Q1 flips only when Q0 was 1 (so Q0 is about to fall).

        #include <stdio.h>
        
        /* A 2-bit ripple counter.
           q0 toggles on every falling clock.
           q1 toggles only when q0 falls. */
        int main(void)
        {
            int clk = 0, prev;
            int q0 = 0, q1 = 0;
            int step;
        
            printf("step clk  Q1 Q0  count\n");
            printf("   0   0   %d  %d     %d\n",
                   q1, q0, q1 * 2 + q0);
        
            for (step = 1; step <= 8; step++) {
                prev = clk;
                clk = 1 - clk;          /* tick */
                if (prev == 1 && clk == 0) {
                    int old0 = q0;
                    q0 = 1 - q0;        /* FF0 */
                    if (old0 == 1)
                        q1 = 1 - q1;    /* FF1 */
                }
                printf("%4d   %d   %d  %d",
                       step, clk, q1, q0);
                printf("     %d\n", q1 * 2 + q0);
            }
            return 0;
        }
        

        Output:

        step clk  Q1 Q0  count
           0   0   0  0     0
           1   1   0  0     0
           2   0   0  1     1
           3   1   0  1     1
           4   0   1  0     2
           5   1   1  0     2
           6   0   1  1     3
           7   1   1  1     3
           8   0   0  0     0

        Read the table: on the odd steps the clock has just risen and the count is unchanged; on the even steps the clock has fallen and the count has moved on, 0, 1, 2, 3, then back to 0. That is the timing diagram in Try it 3, written as text.

        A register is even simpler: an array of bits (see Arrays in C). This program “loads” three numbers into a 4-bit register by storing each bit, rightmost first. Between loads the bits just sit there, which is what a register does between clock edges.

        #include <stdio.h>
        
        /* A 4-bit register: an array of bits.
           Load stores a number. A later clock
           does not change it until we load
           again. */
        int main(void)
        {
            int q[4] = {0, 0, 0, 0};
            int values[3] = {5, 13, 0};
            int v, i, b, n;
        
            for (n = 0; n < 3; n++) {
                v = values[n];
                /* bit 0 is on the right */
                for (i = 0; i < 4; i++) {
                    q[i] = v % 2;
                    v = v / 2;
                }
                printf("loaded %d: ", values[n]);
                for (b = 3; b >= 0; b--)
                    printf("%d", q[b]);
                printf("\n");
            }
            return 0;
        }
        

        Output:

        loaded 5: 0101
        loaded 13: 1101
        loaded 0: 0000

        Try this: extend counter.c to three bits, with q2 toggling when q1 falls. It should count from 0 to 7 and wrap. How many falling clock edges does one full cycle need?

        Try it 4Flip-flop and counter drill

        Choose a type of question. For JK answers you can type 00, 01, 10 or 11, or the word hold, reset, set or toggle when you are asked for the action.

        Summary

        IdeaKey points
        Latch vs flip-flopA latch follows its inputs while they are held (level-sensitive). A flip-flop updates only on a clock edge and holds otherwise.
        D flip-flopQ+ = D on the triggering edge. The usual cell for a register.
        JK flip-flop00 hold, 01 reset, 10 set, 11 toggle. J = K = 1 is a T flip-flop.
        Registern flip-flops with a common clock store an n-bit word. A shift register moves bits along on each edge.
        Ripple counterToggle flip-flops in a chain; each Q clocks the next. A 2-bit counter cycles 00, 01, 10, 11. The count changes on the negative edge of CLK.
        Synchronous counterEvery flip-flop shares the same clock, so there is no ripple delay. Know that it exists; CAPE tracing questions usually use the ripple picture.

        Practice questions

        1. A falling-edge D flip-flop has Q = 1 and D = 0. The clock goes 0 → 1 → 0. What is Q after the rising edge, and after the falling edge?

        Show answer

        After the rising edge Q is still 1 (hold). After the falling edge Q becomes 0, a copy of D.

        2. A JK flip-flop has J = 1, K = 0 and Q = 0. What is Q after one falling edge? What if J and K are both 1 instead?

        Show answer

        J = 1, K = 0 is set, so Q becomes 1. If J = K = 1 it toggles, so Q becomes 1 as well in this case (because it started at 0).

        3. Why is J = K = 1 allowed in a JK flip-flop when S = R = 1 is forbidden in an SR latch?

        Show answer

        The JK flip-flop is edge-triggered and the 11 input is defined as toggle, a useful action. The SR latch is level-sensitive, and S = R = 1 forces Q and Q′ both to the same value, which is inconsistent.

        4. How many flip-flops does a 16-bit register need? What about a counter that must count from 0 to 15?

        Show answer

        16 flip-flops for the register (one per bit). A 0-to-15 counter also needs 4 flip-flops, because 24 = 16 patterns.

        5. A 2-bit ripple counter holds 10 (decimal 2). After one falling clock edge, what are Q1 and Q0? Explain which flip-flops toggled.

        Show answer

        Q0 toggles 0 → 1, which is a rising edge for FF1, so Q1 holds at 1. The new count is 11 (decimal 3).

        6. Why is a long ripple counter slower than a synchronous counter with the same number of bits?

        Show answer

        In a ripple counter each flip-flop is clocked by the previous Q, so a change must propagate down the chain. In a synchronous counter every flip-flop is clocked at the same instant.

        7. A 4-bit register holds 0110. All four D inputs are set to 1, but the clock does not tick. What does the register hold? What does it hold after one triggering edge?

        Show answer

        It still holds 0110, because a register only loads on a clock edge. After the edge it holds 1111.

        Homework

        1. Draw a D flip-flop and a JK flip-flop. For each one write the rule for Q+ and, on the JK, the four-row action table from memory. Check yourself against Parts 2 and 3.
        2. Starting at 00, copy the timing diagram in Try it 3 onto paper for eight clock edges (four pulses). Label every falling edge and the decimal count. Then use Auto-clock to check.
        3. On paper, add a third toggle flip-flop FF2 whose clock is Q1. Complete the 3-bit count from 000 to 111. Then extend counter.c and confirm.
        4. Read The SR Latch again, then explain in four sentences how a clocked JK flip-flop is related to the SR latch and why the extra clock is worth having.

        Exam tips

        Specimen Unit 1 Paper 01 (2021), Item 11. A multiple-choice item about statements on flip-flops, including that a register is made of flip-flops and that a flip-flop is a two-state device. Know those two facts, and be ready to reject a statement that treats a flip-flop as a fault rather than as a memory element.

        2013 Unit 1 Paper 02, Question 1. An early part asks for characteristic features of flip-flops. Answer in terms of two stable states, a clock (edge-triggered update) and the use of flip-flops to build registers and counters. See the worked solution 2013 U1 Q1.

        2009 Unit 1 Paper 02, Question 1 and later papers sometimes combine gates, flip-flops and a counter or a multiplexer in one long question. Being able to trace a 2-bit ripple count, as in Try it 3, is the skill those parts use. See 2009 U1 Q1 and 2024 U1 Q2.

        General advice: always say which edge you are using; trace a counter one flip-flop at a time from the clock towards the high bits; and when a question asks how many flip-flops you need, use one per bit (or 2n states for an n-bit counter). More worked answers are on the CS Solutions page.

        Previous: The SR Latch (lesson 11). Next: Multiplexers, Encoders and Decoders. See also: Logic Gates and Truth Tables and The Ripple Counter Explained (Animation).

        Syllabus link: CAPE Computer Science (CXC A19/U2/21), Unit 1, Module 1: Computer Architecture. Specific Objective 2: describe the basic building blocks of a computer (flip-flops: Data, JK and SR; registers; counters). Specific Objective 3: interpret the interaction among the basic building blocks (data flip-flops, registers).

        Video search terms

        Search YouTube for: "D flip-flop explained", "JK flip-flop truth table", "2-bit ripple counter falling edge", "register from D flip-flops".

        Try it 5Quick quiz

        Tap an answer. All eight questions are self-checks on this lesson.

        Updates

        2026/11/23

        - Removed the Print this lesson button.

        - Fixed a typo in the opening paragraph.

        - Published.

        © 2026 Vedesh Kungebeharry. All rights reserved.

        Character Representation: ASCII and Unicode

        Numbers are only half the story. Every letter you type, every digit on the screen and every punctuation mark is also stored as a pattern of bits. In this lesson you will learn how ASCII gives each common English character a number, how those numbers are organised, and how Unicode (usually stored as UTF-8) extends the idea to every writing system. In C a char is just a small whole number, so the same skills you used in Number Bases: Binary, Octal and Hexadecimal will let you work with text.

        What you will learn

        • Why a computer stores characters as numbers, and what a character set is.
        • The 7-bit ASCII codes for letters, digits and punctuation, including the useful anchors 65, 97 and 48, and the gap of 32 between a capital and its small letter.
        • The difference between the character '7' and the number 7, and how a C string stores a hidden '\0' terminator.
        • What Unicode is, and how a code point such as U+00E9 is written.
        • How UTF-8 stores every code point in one to four bytes, keeps ASCII as a single byte, and why café is 4 characters but 5 bytes.

        Part 1: Characters are numbers

        A computer can only store bits. To store the letter A it must agree, once and for all, which pattern of bits means A. A character set is that agreement: a list that maps each character to a number (its code, or, in Unicode, its code point). The program then stores the number in binary, just like any other whole number.

        Two programs can only share text correctly if they use the same character set, or compatible ones. That is why standards such as ASCII and Unicode matter. If one program thinks 65 means A and another thinks 65 means something else, the file will look like garbage when it is opened.

        Part 2: ASCII

        ASCII (the American Standard Code for Information Interchange) is a 7-bit character set. With 7 bits there are 27 = 128 possible codes, numbered 0 to 127. Codes 0 to 31 (and 127) are control codes such as newline and tab; they do not print a glyph. Codes 32 to 126 are the printable characters: space, punctuation, digits, and the English letters.

        You do not need to memorise the whole table, but three anchors are worth knowing cold, because almost every exam item is a short walk from one of them:

        • ‘A’ = 65. The capital letters then run in order: B is 66, C is 67, …, Z is 90.
        • ‘a’ = 97. The small letters run from 97 to 122. The gap between a capital and the matching small letter is always 32, which is one bit: bit 5 flips from 0 to 1.
        • ‘0’ = 48 (the character zero, not the number 0). The digit characters then run to ‘9’ = 57.

        Worked example 1: the code of a letter

        What is the ASCII code of ‘C’? Start at A = 65. C is two letters on, so 65 + 2 = 67. In binary that is 01000011. What about ‘c’? The small letter is the capital plus 32, so 67 + 32 = 99, or 01100011. The only bit that changed is bit 5.

        Worked example 2: the character 7 is not the number 7

        The character '7' has code 48 + 7 = 55. If you write printf("%d", '7'); in C, the program prints 55, not 7, because %d prints the code as a number. To turn the character into the integer 7 you subtract '0': '7' - '0' is 55 − 48 = 7. That subtraction is the standard way to convert a digit character into its numeric value, and it works because the digit codes are consecutive.

        Worked example 3: counting bits and bytes

        A 7-bit ASCII message of 10 characters needs 10 × 7 = 70 bits. In practice, ASCII is almost always stored in 8-bit bytes, with the top bit 0, so the same message occupies 10 bytes (80 bits). If the question asks for bits in “pure 7-bit ASCII”, use 7; if it asks how the text is stored in a file or in C, use 8-bit bytes. Say which one you are counting.

        Use the chart below to confirm the anchors, then step through nearby codes. The case button flips a letter between capital and small, which is the same as adding or subtracting 32. For any ASCII character the UTF-8 line will show a single byte, equal to the code itself.

        Try it 1ASCII and Unicode chart explorer

        Tap a character, or step through the printable ASCII codes. The panel shows the glyph, the decimal code, the Unicode code point, the bit pattern, and the UTF-8 bytes. The case button flips a letter by 32.

        ·
        binary
        UTF-8

        Part 3: Unicode and UTF-8

        ASCII only covers English letters, digits and a handful of punctuation. A worldwide character set is needed for accented letters, other alphabets, and scripts such as Chinese. Unicode gives every character a single code point, written U+ then a hexadecimal number. A is U+0041 (still 65). The letter é is U+00E9 (233). The euro sign is U+20AC (8364). Unicode is the list of numbers; it is not, by itself, a way of storing them in a file.

        The usual way to store Unicode in a file or on a network is UTF-8. UTF-8 uses one, two, three or four bytes, depending on the code point:

        • Codes 0 to 127 (all of ASCII) use one byte, equal to the ASCII byte. The leading bit is 0. That is why an English UTF-8 file looks identical to the same text saved as ASCII.
        • Codes 128 to 2047 use two bytes. The first byte starts 110, the second starts 10, and the remaining 11 bits hold the code point.
        • Larger codes use three bytes (leading 1110, then two continuation bytes starting 10) or four bytes (leading 11110, then three continuations).

        The prefix bits are not decoration: they tell a decoder where a character starts and how many bytes it occupies. A continuation byte always starts with 10, so it can never be mistaken for the start of a new character.

        Worked example 4: encoding é in UTF-8

        The letter é has code point U+00E9, which is 233 in decimal. 233 is bigger than 127 and smaller than 2048, so UTF-8 uses two bytes. 233 in binary is 11101001, which is 11 bits if you write it as 00011101001. Those 11 payload bits are split as 00011 on the first byte and 101001 on the second:

        1. First byte: prefix 110, then 00011, giving 11000011, which is 195 or C3 in hex.
        2. Second byte: prefix 10, then 101001, giving 10101001, which is 169 or A9 in hex.

        So é is stored as the two bytes C3 A9. Check this in the builder below: the teal bits are the prefixes, and the orange bits are the payload, which should reassemble to 233.

        Worked example 5: four characters, five bytes

        The word café has four characters: c, a, f, and é. The first three are ASCII, so each occupies one byte (99, 97, 102). The é occupies two bytes (195, 169). The file is therefore 5 bytes long, even though you count four characters on the screen. If a question gives you a mixed word and asks for the size in UTF-8, count one byte for each ASCII character and two (or more) for each character above 127. Do not assume that one character is one byte once Unicode is involved.

        Worked example 6: a three-byte code

        The euro sign € is U+20AC, which is 8364. That is bigger than 2047, so UTF-8 uses three bytes. The 16 payload bits of 20AC are placed after a leading 1110 and two continuation prefixes of 10, giving E2 82 AC (226, 130, 172). You do not have to do this by hand in every exam, but you should be able to say how many bytes it needs, and why that is more than one.

        In the builder, pick a code point and watch the prefix bits and the payload bits. Then compare a word that is all ASCII with one that contains é: the byte count and the character count only stay equal while every code is below 128.

        Try it 2UTF-8 byte builder

        Pick a code point. Teal bits are the UTF-8 prefix (0, 110, 10, 1110, …); orange bits are the payload that encodes the code point. Then compare a short word’s character count with its UTF-8 byte count.

        A last warning about file size: some editors also write a short byte-order mark at the start of a UTF-8 file, and some systems still use a one-byte-per-character encoding for codes 128 to 255 (sometimes called extended ASCII, or Latin-1). Those encodings are not UTF-8. The letter é is byte 233 in Latin-1, but the two bytes C3 A9 in UTF-8. If a file looks almost right except for the accented letters, the usual cause is that one program saved it in Latin-1 and another opened it as UTF-8, or the other way around. When a question just says "Unicode text", assume UTF-8 unless it names a different encoding.

        You now have two separate counts to keep straight: the number of characters a person reads, and the number of bytes a computer stores. For ASCII they are equal (plus the C terminator, if the question is about a C string). For UTF-8 they are equal only while every code point is below 128. The live builder is there so you can check both counts on the same word, instead of guessing.

        Part 4: Characters in C

        In C, a char is a small whole number. Writing 'A' is just a convenient way of writing 65. You can add 1 to a character, subtract two characters, or print a character with %c and its code with %d. The first program below prints the codes of A to E, shows that 'a' - 'A' is 32, and shows that '7' as a number is 55, not 7. Run it, then change the loop limits and compile again.

        #include <stdio.h>
        
        int main(void)
        {
            char c;
            char d = '7';
        
            /* a char is a small whole number */
            for (c = 'A'; c <= 'E'; c++)
                printf("%c = %d\n", c, c);
        
            printf("'a' - 'A' = %d\n", 'a' - 'A');
            printf("'x' + 1 = '%c'\n", 'x' + 1);
        
            /* the character '7' is not 7 */
            printf("'7' as a number: %d\n", d);
            printf("'7' - '0' = %d\n", d - '0');
            return 0;
        }
        

        Output:

        A = 65
        B = 66
        C = 67
        D = 68
        E = 69
        'a' - 'A' = 32
        'x' + 1 = 'y'
        '7' as a number: 55
        '7' - '0' = 7

        A C string is an array of characters that ends with a hidden terminator, the null character '\0', whose code is 0. The string "Hi" therefore occupies three bytes: H, i, and the terminator. The second program walks a string, turns each small letter into a capital by subtracting 32, and then prints the length: that length is the number of visible characters, and the terminator sits in one extra byte after them. Remember the extra byte whenever a question asks how a C string is stored; do not include the terminator when the question is only about how many characters are printed on the screen.

        #include <stdio.h>
        
        int main(void)
        {
            char msg[] = "Island Class 2026!";
            int i = 0;
        
            /* change small letters to capitals:
               capitals are 32 lower in ASCII */
            while (msg[i] != '\0') {
                if (msg[i] >= 'a' && msg[i] <= 'z')
                    msg[i] = msg[i] - 32;
                i++;
            }
            printf("%s\n", msg);
            printf("%d characters", i);
            printf(" + 1 for '\\0'\n");
            return 0;
        }
        

        Output:

        ISLAND CLASS 2026!
        18 characters + 1 for '\0'

        Try it 3Character codes drill

        Use the anchors: A = 65, a = 97, the character 0 = 48. The gap between a capital and the matching small letter is 32. C strings have a hidden terminator.

        Summary

        • A character set maps each character to a number. ASCII is a 7-bit set with 128 codes, 0 to 127.
        • Anchors: 'A' = 65, 'a' = 97, '0' = 48. A small letter is always 32 more than its capital. The character '7' has code 55, not 7.
        • Unicode gives every character a code point (U+....). UTF-8 stores a code point in one to four bytes. ASCII codes stay as a single byte, so English UTF-8 looks like ASCII.
        • One character is not always one byte: café is 4 characters and 5 UTF-8 bytes. A C string has an extra '\0' byte at the end.

        Practice questions

        1. How many different characters can 7-bit ASCII represent? Why?

        Show answer

        128, because 27 = 128. The codes run from 0 to 127.

        2. What is the ASCII code of 'C', and of 'c'? Show a line of working from an anchor.

        Show answer

        'A' = 65, so 'C' is 65 + 2 = 67. The small letter is the capital plus 32, so 'c' is 67 + 32 = 99.

        3. In C, what does printf("%d", '0'); print, and why is it not 0?

        Show answer

        It prints 48. The character '0' has code 48, and %d prints that code as a number, not the glyph 0.

        4. A C string "Hi" is stored in how many bytes? Name the extra one.

        Show answer

        3 bytes: H, i, and the hidden '\0' terminator.

        5. What is Unicode, and how is a code point usually written?

        Show answer

        A worldwide set of code points, one for every character. A code point is written U+ followed by a hexadecimal number, such as U+0041 for A.

        6. Why does an English UTF-8 file look identical to the same text saved as ASCII?

        Show answer

        The first 128 UTF-8 codes use the same single bytes as ASCII. The leading bit is 0, and the remaining 7 bits are the ASCII code.

        7. The word café has 4 characters. In UTF-8 it occupies 5 bytes. Why?

        Show answer

        c, a and f are ASCII, so each uses one byte. The accented e has a code above 127, so it uses two bytes. 3 + 2 = 5.

        8. Encode é (code 233) as UTF-8 and give the two bytes in decimal and hex.

        Show answer

        233 needs two bytes: 195 and 169, or C3 A9. The first byte starts 110, the second starts 10, and the 11 payload bits are 00011101001.

        Homework

        • On paper, write the ASCII codes of A, C, a, 0 and 7, each in decimal and in 8-bit binary. Check them in the chart explorer.
        • Using the UTF-8 builder, copy the bit pattern of é and of A, and in one sentence explain why A is one byte while é is two.
        • Change ascii.c so the loop prints '0' to '9'. Predict the first and last numbers before you compile.
        • Count the UTF-8 bytes in your own first name (including any accented letter). State the character count and the byte count separately.

        Mastery quiz: Character Representation

        This 10-question quiz is separate from the short Quick quiz at the end of the lesson. Score 8/10 or higher to earn this lesson’s badge. Your best score is saved in this browser on this device.

        Mastery quiz: Character Representation: ASCII and Unicode

        Your course badges: loading saved progress…

        View badges

          No course badges earned yet. Score 8/10 in a lesson quiz to earn its badge.

          Saved in this browser on this device. Clearing browser data may remove your badges.

          Answer all 10 questions. Earn this lesson’s badge at 8/10 or higher. Read the explanations, revisit the Try it activities and retry as often as you need. These are self-study badges, not formal grades.

          1. How many different characters can 7-bit ASCII represent?
          2. What is the ASCII code of 'C'?
          3. A small letter is always how much more than its capital in ASCII?
          4. In C, what does printf("%d", '0'); print?
          5. A C string "Hi" is stored in how many bytes?
          6. What is Unicode?
          7. Why does an English UTF-8 file look identical to the same text saved as ASCII?
          8. The word café has 4 characters. In UTF-8 it occupies 5 bytes. Why?
          9. The UTF-8 encoding of é (code 233) is which pair of bytes?
          10. To turn the character '7' into the integer 7 in C, you...

          Exam tips

          Character representation in Unit 1 Paper 01 and Paper 02. Specific Objective 4 names character representation alongside number bases and fixed- and floating-point numbers. A short item may ask for the ASCII code of a letter, how many bits a message needs, or why a character is stored as a number. Use the anchors (65, 97, 48) and show a line of working.

          Paper 02 questions that use text in C (for example in later modules on programming) often hang on the difference between the character '7' and the number 7, or on the extra '\0' at the end of a string. The programs in Part 4 are worth practising for those as well.

          General advice: say whether you are counting bits, bytes or characters; include the terminator only when the question is about a C string; and never assume that one character is one byte once Unicode is involved. More worked answers are on the CS Solutions page.

          Previous: Fixed-Point and Floating-Point Numbers. Next: The SR Latch (lesson 11). See also: Strings in C: char Arrays, %s, fgets, and strlen and Variables, format specifiers and printf.

          Syllabus link: CAPE Computer Science (CXC A19/U2/21), Unit 1, Module 1: Computer Architecture. Specific Objective 4: explain how data is represented in the computer (character representation).

          Video search terms

          Search YouTube for: "ASCII table explained", "ASCII vs Unicode vs UTF-8", "characters as numbers in C", "UTF-8 encoding explained".

          Try it 4Quick quiz

          Tap an answer. All eight questions are self-checks on this lesson.

          Updates

          2026/11/24

          - Rebuilt the lesson with fuller explanations, diagrams and new Try it simulations.

          2026/11/23

          - Removed the Print this lesson button.

          - Reworded some sentences so they speak directly to students.

          - Published.

          © 2026 Vedesh Kungebeharry. All rights reserved.

          Fixed-Point and Floating-Point Numbers

          Two’s complement handles whole numbers, but programs also need fractions (a price of $12.95, a speed of 9.81 m/s²) and numbers that are very large or very small (the mass of the Earth, the size of an atom). In this lesson you will learn how binary fractions work, how a fixed-point format stores them, and how a floating-point format uses a sign, a mantissa and an exponent to cover a huge range of values, at the cost of some precision. You will also see why 0.1 + 0.1 + ... does not quite make 1 in C. The lesson uses a small 9-bit format you can decode by hand, of the kind that appears in CAPE papers. Real hardware uses many more bits, but the three fields and the method are the same.

          What you will learn

          • How to read and write binary fractions (place values 1/2, 1/4, 1/8, …).
          • What a fixed-point number is, and its strengths and weaknesses.
          • How a floating-point number is made of a sign bit, a mantissa and an exponent.
          • How to decode and encode numbers in a small floating-point format of the kind used in CAPE questions.
          • What normalisation means and why it matters.
          • The trade-off between range and precision, and why some decimals cannot be stored exactly (with proof in C).

          Part 1: Binary fractions

          In decimal, the columns after the point are worth 1/10, 1/100, 1/1000. In binary, each column after the binary point is worth half the one to its left: 1/2, 1/4, 1/8, 1/16, and so on.

          Place value421.1/21/41/8
          101.11101.110

          101.11 = 4 + 1 + 1/2 + 1/4 = 5.75. The same method works for any length: write the place values above the bits, add the columns that hold a 1, and stop when you run out of bits. 0.1 in binary is 1/2, 0.01 is 1/4, 0.001 is 1/8, and so on.

          Worked example A. Convert 110.011 to decimal. Place values 4, 2, 1, then 1/2, 1/4, 1/8. The 1s sit in the 4, 2, 1/4 and 1/8 columns: 4 + 2 + 0.25 + 0.125 = 6.375.

          Worked example B (the other way). Write 5.625 in binary. 5 is 101. The fraction 0.625 = 1/2 + 1/8, so the bits after the point are 101: 101.101. Check: 4 + 1 + 0.5 + 0.125 = 5.625. Two useful facts:

          • Moving the binary point one place to the right doubles a number; one place to the left halves it. (In decimal, moving the point multiplies or divides by 10.)
          • Only fractions made from halves, quarters, eighths and so on can be written exactly. 0.75 = 0.11 exactly, but 0.1 (one tenth) is 0.000110011001100… in binary, repeating for ever, just as 1/3 = 0.3333… in decimal.

          Part 2: Fixed-point numbers

          A fixed-point format puts the binary point in the same place in every number. For example, an 8-bit format with 4 bits before the point and 4 after can store 0000.0000 (0) up to 1111.1111 (15.9375), in steps of 1/16. (The integers in Signed Integers: Sign and Magnitude, Ones’ and Two’s Complement are fixed point with the point after the last bit.)

          • Advantages: simple and fast (the same adder works, because you can pretend the point is not there and put it back afterwards); every value is exact to the nearest step, which suits money counted in cents.
          • Disadvantages: the range is small, and the step size is the same for every number. You cannot store both 0.0001 and 1,000,000 in the same 8 or 16 bits.

          Try it 1 is an 8-bit 4.4 format: four bits before the point and four after. The largest value is 1111.1111 = 15 + 15/16 = 15.9375, and the smallest positive step is 0000.0001 = 1/16 = 0.0625. If you need a finer step, you can move the point one place left (3.5 format, steps of 1/32) but then the whole-number part only goes up to 7, so the range shrinks. That is the trade-off fixed point always makes.

          Try it 1Fixed-point explorer

          An 8-bit fixed-point number with 4 bits before and 4 bits after the binary point. Tap the bits. The teal dot is the point, and it never moves: every value uses the same place values.

          Part 3: Floating point: sign, mantissa and exponent

          Scientists write very large and very small numbers in standard form: 6,500,000 = 0.65 × 107. The digits 0.65 carry the precision and the power 7 says where the point goes. A floating-point number does the same in binary:

          value = ± mantissa × 2^exponent
          • The sign bit: 0 for positive, 1 for negative.
          • The mantissa (also called the significand): the significant bits of the number, written as a binary fraction 0.xxxxx.
          • The exponent: a whole number that says how many places to move the binary point, right if positive, left if negative. It is often stored in two’s complement so it can be negative.

          The point floats: a big exponent moves it far to the right (huge numbers), and a negative exponent moves it to the left (tiny fractions). The same few bits can cover a huge range. That is the whole idea of the format: the mantissa holds the significant bits, and the exponent says where to put the point, instead of leaving empty columns of zeros at one end or the other.

          A small CAPE-style format

          Exam questions use tiny formats so you can work by hand. In this lesson we use 9 bits: 1 sign bit, then a 3-bit exponent, then a 5-bit mantissa, with the mantissa read as 0.m1m2m3m4m5. The exponent is in two’s complement, so it runs from −4 to 3. Always read the question carefully: it will tell you the order and size of the fields, and sometimes how the exponent is stored. (For exponents from 0 to 3, unsigned and two’s complement give the same value.)

          Decoding: three steps

          1. Split the bits into sign, exponent and mantissa.
          2. Work out the exponent in decimal.
          3. Write 0.mantissa, move the binary point exponent places (right if positive), then convert to decimal and apply the sign.

          Worked example 1. Decode 0 011 11010.

          Sign      0          positive
          Exponent  011     =  3
          Mantissa  0.11010
          Move the point 3 places right:
                    110.10  =  4 + 2 + 1/2  =  6.5

          Worked example 2. Decode 1 010 10100. Sign 1 (negative); exponent 010 = 2; mantissa 0.10100. Moving the point 2 places right gives 10.100 = 2.5, so the value is −2.5.

          Worked example 3 (negative exponent). Decode 0 110 11000. The exponent 110 in 3-bit two’s complement is −4 + 2 = −2. Mantissa 0.11000; move the point 2 places left: 0.0011000 = 1/8 + 1/16 = 0.1875.

          A useful check is to do the multiplication in decimal: 0.11000 is 0.5 + 0.25 = 0.75, and 0.75 × 2−2 = 0.75 ÷ 4 = 0.1875, the same answer. When the exponent is negative, you are shrinking the mantissa, not growing it. Write the extra 0s after the point so you can see the place values clearly.

          Encoding

          Worked example 4. Store 3.75 in the same format. 3.75 = 11.11 in binary. Move the point so the number reads 0.1...: 11.11 = 0.1111 × 22. Sign 0; exponent 2 = 010; mantissa 11110 (pad with a trailing 0 to fill 5 bits). Answer: 0 010 11110.

          Always pad or trim the mantissa to the width the format allows. If the binary fraction is longer than five bits you have to round (or chop) it, and that is one source of rounding error. If you forget to normalise and write 0.01111 × 23 instead, you would store 0 011 01111, which is a different pattern for the same value but wastes a leading 0 in the mantissa. Worked example 4 is already normalised, because the mantissa starts 0.1.

          Normalisation

          The same number can often be written in several ways: 3 = 0.11 × 22 = 0.011 × 23. A floating-point number is normalised when the mantissa starts 0.1 (its first bit is 1), so no mantissa bits are wasted on leading zeros. In our format, 0 011 01100 and 0 010 11000 both mean 3, but only the second is normalised. Normalising gives the most precision possible, and makes every value have one standard pattern.

          To normalise, shift the mantissa left until its first bit is 1, and subtract 1 from the exponent for each shift. For 0 011 01100 the mantissa is 0.01100; one shift left gives 0.11000 and the exponent drops from 3 to 2, so the normalised pattern is 0 010 11000. Check: 0.11000 × 22 = 11.000 = 3, the same value. If the exponent cannot go any lower, the number cannot be normalised in this format (it underflows toward zero). With two’s complement mantissas, a normalised negative mantissa starts 1.0 instead. Follow whatever format the question gives; this lesson uses an unsigned 0.m mantissa, which is the usual CAPE convention.

          Try it 2Floating-point decoder

          9 bits: sign (S), a 3-bit exponent (E) and a 5-bit mantissa (M) read as 0.m. Tap the bits or an example. The diagram moves the binary point by the exponent. The flag tells you whether the pattern is normalised. Switch how the exponent is read to see why the question must tell you the format.

          
          

          Part 4: Range, precision and rounding

          Every floating-point format shares its bits between the mantissa and the exponent:

          • More mantissa bits give more precision (more significant figures).
          • More exponent bits give more range (bigger and smaller numbers).

          In our 9-bit format the largest value is 0 011 11111 = 0.11111 × 23 = 111.11 = 7.75, and the smallest positive normalised value is 0 100 10000 = 0.1 × 2−4 = 1/32 = 0.03125. You can confirm both ends in Try it 2 by setting those patterns.

          A number like 6.6 cannot be stored: 110.10 (6.5) and 110.11 (6.75) are neighbours, and there is nothing in between. The computer stores the nearest value, which causes a rounding error. The gaps get larger as the exponent grows, because a one-step change in the last mantissa bit is then worth a larger place value. Two more problems to name:

          • Overflow: the exponent needed is bigger than the largest exponent (the number is too big).
          • Underflow: the number is so close to 0 that the exponent needed is smaller than the most negative exponent, so it is stored as 0.

          For interest: real computers use the IEEE 754 standard. A C float has 1 sign bit, 8 exponent bits and 23 mantissa bits (about 7 decimal digits), and a double has 1, 11 and 52 (about 15 to 16 digits). The idea is exactly the one above; IEEE adds a few tricks (a biased exponent and a hidden leading 1) that CAPE does not require.

          Part 5: Floating point in C

          This program shows that 0.1 is not stored exactly, and that the tiny errors add up. %.20f asks printf for 20 decimal places. (See int vs float: Truncation, Binary, and Choosing the Right Specifier for more on float and double.)

          #include <stdio.h>
          
          int main(void)
          {
              float f = 0.1f;
              double d = 0.1;
              double sum = 0.0;
              int i;
          
              /* 0.1 has no exact binary form */
              printf("float  0.1 = %.20f\n", f);
              printf("double 0.1 = %.20f\n", d);
          
              for (i = 0; i < 10; i++)
                  sum = sum + 0.1;
              printf("ten 0.1s  = %.17f\n", sum);
              if (sum == 1.0)
                  printf("sum equals 1.0\n");
              else
                  printf("sum is NOT 1.0\n");
          
              /* 0.75 = 0.11 in binary: exact */
              printf("0.75 = %.20f\n", 0.75);
              return 0;
          }
          

          Output:

          float  0.1 = 0.10000000149011611938
          double 0.1 = 0.10000000000000000555
          ten 0.1s  = 0.99999999999999989
          sum is NOT 1.0
          0.75 = 0.75000000000000000000

          The float is wrong in the 9th decimal place and the double in the 18th, but neither is exact. 0.75 is exact because it is 0.11 in binary. Rule: never use == to compare floating-point results in C. Check that the difference is very small instead, and store money as a whole number of cents.

          The next program decodes our 9-bit format exactly as you do by hand. The bits arrive as a string of characters (see Strings in C: char Arrays, %s, fgets, and strlen); b[i] - '0' turns the character '0' or '1' into the number 0 or 1.

          #include <stdio.h>
          
          /* Decode a 9-bit pattern:
             1 sign bit, 3 exponent bits
             (two's complement), 5 mantissa bits.
             Value = +/- 0.mantissa x 2^exponent */
          double decode(const char *b)
          {
              int sign = b[0] - '0';
              int e = (b[1] - '0') * 4
                    + (b[2] - '0') * 2
                    + (b[3] - '0');
              double m = 0.0, place = 0.5;
              int i;
          
              if (e > 3)
                  e = e - 8;    /* negative */
              for (i = 4; i < 9; i++) {
                  m = m + (b[i] - '0') * place;
                  place = place / 2;
              }
              while (e > 0) { m = m * 2; e--; }
              while (e < 0) { m = m / 2; e++; }
              return sign ? -m : m;
          }
          
          int main(void)
          {
              printf("%g\n", decode("001111100"));
              printf("%g\n", decode("101010100"));
              printf("%g\n", decode("011011000"));
              return 0;
          }
          

          Output:

          7
          -2.5
          0.1875

          These are 0 011 11100, Worked example 2 and Worked example 3. Try this: add a line to decode Worked example 1 and check that it prints 6.5.

          Try it 3Fractions and floating-point drill

          Floating-point questions use 1 sign bit, a 3-bit exponent and a 5-bit mantissa, with exponents from 0 to 3. Type decimals with a point (for example 2.75).

          Summary

          IdeaKey points
          Binary fractionsPlace values after the point: 1/2, 1/4, 1/8, ... Some decimals (like 0.1) never end in binary.
          Fixed pointThe point is in a fixed place. Simple and exact to one step size, but a small range.
          Floating pointValue = ± 0.mantissa × 2exponent. Sign bit, mantissa (precision), exponent (range).
          DecodingSplit the fields; find the exponent; move the point; convert; apply the sign.
          NormalisedThe mantissa starts 0.1: no wasted leading zeros, maximum precision, one pattern per value.
          Trade-offMore mantissa bits = more precision; more exponent bits = more range.
          In Cfloat and double are IEEE 754 floating point. Expect small rounding errors; don’t compare with ==.

          Practice questions

          1. Convert 110.011 to decimal.

          Show answer

          4 + 2 + 1/4 + 1/8 = 6.375.

          2. Write 9.625 as a binary fixed-point number with 4 bits before and 4 bits after the point.

          Show answer

          9 = 1001 and 0.625 = 1/2 + 1/8 = .1010. Answer: 1001.1010.

          3. Using 1 sign bit, a 3-bit two’s complement exponent and a 5-bit mantissa, decode 1 011 10011.

          Show answer

          Negative; exponent 3; 0.10011 × 23 = 100.11 = 4.75. Value: −4.75.

          4. Store 1.25 in the same format, normalised.

          Show answer

          1.25 = 1.01 = 0.101 × 21. Sign 0, exponent 001, mantissa 10100: 0 001 10100.

          5. Is 0 010 01110 normalised? If not, normalise it.

          Show answer

          No: the mantissa starts 0.0. Shift left once (10110... becomes 11100) and lower the exponent from 2 to 1: 0 001 11100. Both equal 0.0111 × 4 = 1.75.

          6. A format keeps 12 bits in total. Explain what happens if you move one bit from the mantissa to the exponent.

          Show answer

          The range gets bigger (larger and smaller numbers can be stored) but the precision drops (fewer significant bits, so bigger rounding errors).

          7. Why does adding 0.1 ten times in C not give exactly 1.0?

          Show answer

          0.1 has no exact binary form, so the stored value is very slightly off. Each addition also rounds, and the small errors add up.

          Homework

          1. List every positive value that the 9-bit format in this lesson can hold with exponent 000. What step size do you notice? Now do the same for exponent 011. What happens to the gaps?
          2. Encode 0.375, 2.5 and 7 in the 9-bit format (normalised), then check each with Try it 2.
          3. Write a C program that adds 0.1 to a float 1000 times and prints the result with %.6f. Then do the same with an int counting tenths (add 1 each time, and print the count divided by 10.0). Which is accurate, and why?
          4. Research: how many bits are in the exponent and mantissa of an IEEE 754 single-precision number? Find the largest value a C float can hold (look up FLT_MAX).

          Mastery quiz: Fixed-Point and Floating-Point Numbers

          This 10-question quiz is separate from the short Quick quiz at the end of the lesson. Score 8/10 or higher to earn this lesson’s badge. Your best score is saved in this browser on this device.

          Mastery quiz: Fixed-Point and Floating-Point Numbers

          Your course badges: loading saved progress…

          View badges

            No course badges earned yet. Score 8/10 in a lesson quiz to earn its badge.

            Saved in this browser on this device. Clearing browser data may remove your badges.

            Answer all 10 questions. Earn this lesson’s badge at 8/10 or higher. Read the explanations, revisit the Try it activities and retry as often as you need. These are self-study badges, not formal grades.

            1. What is 10.01 in decimal?
            2. In a floating-point number, which part mainly decides the range?
            3. In a floating-point number, which part mainly decides the precision?
            4. In this lesson’s 9-bit format (0.m mantissa), what is 0 010 11000?
            5. A floating-point number is normalised when...
            6. In 3-bit two’s complement, the exponent 111 stands for...
            7. Why can a computer not store 0.1 exactly in binary floating point?
            8. Which is an advantage of fixed point over floating point?
            9. To normalise 0 011 01100 in this lesson’s 9-bit format you should write...
            10. In this lesson’s 9-bit format, the largest value is...

            Exam tips

            Specimen Unit 1 Paper 02 (2021), Question 1(c). Gives a small floating-point format (a sign bit, a short exponent and a mantissa) and a bit pattern, and asks for its decimal value. The method is exactly Worked examples 1 to 3: label the three fields, give the exponent in decimal, move the point and convert. Marks go to each of these steps, so show them.

            Questions on representation in general. Specific Objective 4 asks you to explain fixed point and floating point. Be ready to define sign, mantissa and exponent in a sentence each, to explain normalisation, and to compare the range and precision of two formats.

            General advice: write the fields with spaces between them before you start; say whether the exponent is positive or negative; and convert your answer back if you have time. More worked answers are on the CS Solutions page.

            Previous: Signed Integers: Sign and Magnitude, Ones’ and Two’s Complement. Next: Character Representation: ASCII and Unicode. See also: int vs float: Truncation, Binary, and Choosing the Right Specifier.

            Syllabus link: CAPE Computer Science (CXC A19/U2/21), Unit 1, Module 1: Computer Architecture. Specific Objective 4: explain how data is represented in the computer (fixed point and floating point numbers: sign, mantissa and exponent).

            Video search terms

            Search YouTube for: "binary fractions explained", "floating point mantissa and exponent", "normalised floating point binary", "why 0.1 + 0.2 is not 0.3".

            Try it 4Quick quiz

            Tap an answer. All eight questions are self-checks on this lesson.

            Updates

            2026/11/24

            - Rebuilt the lesson with fuller explanations, diagrams and new Try it simulations.

            2026/11/23

            - Removed the Print this lesson button.

            - Next lesson now links to Character Representation: ASCII and Unicode.

            - Published.

            2026/11/11

            - Draft written (local file, not yet on the site).

            © 2026 Vedesh Kungebeharry. All rights reserved.

            Signed Integers: Sign and Magnitude, Ones’ and Two’s Complement

            So far every binary number has been positive. But programs need negative numbers too: temperatures, bank balances, the change in a score. A computer has no minus sign, only bits, so it must use some of its bit patterns to stand for negative values. In this lesson you will learn the three methods named in the CAPE syllabus (sign and magnitude, ones’ complement and two’s complement), why almost every computer uses two’s complement, how it turns subtraction into addition, and how to spot signed overflow. These are called fixed-point representations, because the binary point is fixed after the last bit: they hold whole numbers only. Fractions and the moving binary point are in the next lesson.

            What you will learn

            • How to write positive and negative whole numbers in sign and magnitude, ones’ complement and two’s complement.
            • How to read a signed bit pattern back as a decimal number.
            • The range of values each method can hold with n bits, and why two’s complement has one extra negative number.
            • How a computer subtracts by adding the two’s complement.
            • How to recognise signed overflow, and why the carry out is not the overflow flag.
            • How C stores signed char values, and what happens when they go out of range.

            You will need binary conversions from Number Bases: Binary, Octal and Hexadecimal and column addition from Adding Binary Numbers: Carries, Adders and Overflow.

            Part 1: Sign and magnitude

            The simplest idea: use the leftmost bit (the most significant bit, MSB) as a sign, 0 for positive and 1 for negative, and the other bits for the size (magnitude) of the number.

            +45  =  0 010 1101
            −45  =  1 010 1101
                    ^
                    sign bit

            Reading a pattern is just as direct. Cover the leftmost bit, convert the other seven bits to decimal, then attach the sign. So 1000 0111 has sign 1 and magnitude 000 0111 = 7, which is −7. The pattern 0000 0111 is +7. Only the sign bit changed; the magnitude bits stayed the same. That is why the method is easy for people to read.

            In 8 bits, the magnitude has 7 bits, so the range is −127 to +127. This is easy for people to read, but it has two serious problems, and both of them show up in hardware:

            • There are two zeros: 0000 0000 is +0 and 1000 0000 is −0. Two different patterns mean the same value, which wastes a pattern and makes a comparison such as “is this zero?” need an extra check.
            • Ordinary binary addition gives wrong answers. The adder from Adding Binary Numbers: Carries, Adders and Overflow does not know about a sign bit, so it treats every 1 as a place value.

            Worked example 1: why +5 + (−5) fails. In 8-bit sign and magnitude, +5 is 0000 0101 and −5 is 1000 0101. Add them as ordinary binary:

              0000 0101     (+5)
            + 1000 0101     (−5)
              --------- 
              1000 1010

            The result 1000 1010 has sign 1 and magnitude 000 1010 = 10, so it reads as −10, not 0. The hardware would need extra circuits to compare the two signs, decide whether to add or subtract the magnitudes, and then choose a sign for the answer. That is a lot of extra logic for every addition.

            Part 2: Ones’ complement

            To make a negative number in ones’ complement, write the positive number and then flip every bit (0 becomes 1 and 1 becomes 0). The leftmost bit still shows the sign.

            +45  =  0010 1101
            −45  =  1101 0010   (every bit flipped)

            To read a negative ones’ complement pattern, flip the bits again and read the result as a positive number, then attach a minus. For 1101 0010: flip → 0010 1101 = 45, so the pattern is −45. If the leftmost bit is 0, just read the pattern as unsigned binary.

            The range in 8 bits is again −127 to +127, and there are still two zeros: 0000 0000 is +0 and 1111 1111 (every bit flipped) is −0. Addition is better than in sign and magnitude, but it needs a special rule: any carry out of the leftmost column has to be added back in at the right. That end-around carry costs an extra add step.

            Worked example 2 (4 bits): +3 + (−2) in ones’ complement. +3 is 0011. +2 is 0010, so −2 is the flip, 1101.

                      0011     (+3)
                    + 1101     (−2)
                      ----
                    1 0000
            Add the carry around: 0000 + 1 = 0001 = +1.  ✔

            The true answer is 1, and after the end-around carry the 4-bit result is right. Without that extra add you would have been left with 0000, which is wrong. Computers can do this, but it is slower than a single pass through the adder, and the two zeros are still a nuisance. Two’s complement, next, removes both issues with one extra trick: flip, then add 1.

            Part 3: Two’s complement

            Two’s complement is the representation almost every modern processor uses for signed integers, including the signed char, short and int types you will meet in C in Part 6. To make a negative number: write the positive number in the agreed width, flip every bit, then add 1.

            +45            =  0010 1101
            flip           =  1101 0010
            add 1          =  1101 0011   = −45

            Always write every bit, including leading 0s, before you flip. If you flip a 7-bit pattern and then pad it, the sign bit will be wrong. In an exam, show the flip and the add-1 as two separate lines, just as above. Do not skip to the answer in one step.

            Reading two’s complement: the leftmost bit is worth −128

            The neatest way to understand two’s complement is through place values. In 8 bits, the leftmost column is worth −128 instead of +128. All the other columns keep their usual positive values: 64, 32, 16, 8, 4, 2 and 1. Adding those place values always gives the correct signed number, whether it is positive or negative. You never have to remember a separate reading rule for the sign.

            Place value−1286432168421
            1101 001111010011
            1001 110010011100
            0010 110100101101
            • 1101 0011 = −128 + 64 + 16 + 2 + 1 = −45. ✔
            • 1001 1100 = −128 + 16 + 8 + 4 = −100.
            • 0010 1101 = 32 + 8 + 4 + 1 = +45. If the leftmost bit is 0, the number is positive and you read it exactly as unsigned binary.

            You can also decode a negative pattern by doing flip and add 1 again: the same two steps always take you back to the positive partner. For 1001 1100: flip → 0110 0011, add 1 → 0110 0100 = 100, so the pattern is −100. Use whichever method you can do cleanly, and check the other way if you have time. Place values are usually faster once you are used to the −128 column.

            A shortcut

            Working from the right, copy every bit up to and including the first 1, then flip all the bits to its left. For +45 = 0010 1101: the first bit on the right is already a 1, so copy it and flip the rest: 1101 0011 = 1101 0011. For +12 = 0000 1100 the first 1 from the right is the 4s bit, so you copy 100 and flip the left five bits: 1111 0100. Check: −128 + 64 + 32 + 16 + 4 = −12. Use the shortcut to check your answers, but show flip and add 1 in an exam, because that is the method the mark scheme expects.

            Why computers use two’s complement

            • There is only one zero (0000 0000). Flip 0000 0000 and you get 1111 1111; add 1 and you get 1 0000 0000. The carry out is lost in 8 bits and you are back at 0000 0000. So +0 and −0 are the same pattern.
            • Ordinary binary addition just works, for positive and negative numbers alike. The same adder circuit handles both, and subtraction becomes addition (Part 5).
            • Because the spare pattern is not wasted on −0, the range has one extra negative number: 8 bits hold −128 to +127. The extra value is the pattern 1000 0000, which is a 1 in the −128 column and zeros everywhere else.

            A helpful picture is a wheel. The 256 possible 8-bit patterns sit around a circle. Starting at 0 and moving clockwise you count 1, 2, … up to 127; the next step lands on −128, then −127, … down to −1, which sits next to 0 again. Adding one is just a step clockwise; when you step past 127 you wrap to −128, and that wrap is overflow. Try it 1 is that wheel, with a bit flipper under it so you can also build any pattern by hand.

            Try it 1One pattern, four readings

            Tap the bits, or walk the wheel with +1 and −1. The same 8 bits are read as unsigned, sign and magnitude, ones’ complement and two’s complement. The pointer shows the two’s complement value. Tap Negate to watch flip-and-add-1. Try +1 at 127 to see overflow wrap to −128.

            Part 4: Ranges

            With n bits there are 2n different patterns, and that number never changes. What changes from one scheme to another is how those patterns are shared out between the negative numbers, zero and the positive numbers.

            SchemeRange with n bits4 bits8 bits16 bits
            Unsigned0 to 2n − 10 to 150 to 2550 to 65,535
            Sign and magnitude−(2n−1 − 1) to 2n−1 − 1−7 to 7−127 to 127−32,767 to 32,767
            Ones’ complementsame as sign and magnitude−7 to 7−127 to 127−32,767 to 32,767
            Two’s complement−2n−1 to 2n−1 − 1−8 to 7−128 to 127−32,768 to 32,767

            Memorise this range for two’s complement in 8 bits, −128 to 127, and the pattern for each end: the most negative is a 1 followed by all 0s (1000 0000 = −128) and the largest positive is a 0 followed by all 1s (0111 1111 = 127). For 4 bits the same shapes give 1000 = −8 and 0111 = 7. See also the worked solution Solution to the largest and smallest two’s complement numbers using 4 bits.

            A quick way to get the n-bit two’s complement range is: the most negative is −2n−1, the most positive is one less than the size of that power. For 6 bits, 25 = 32, so the range is −32 to 31. For sign and magnitude with 6 bits, one pattern is spent on −0, so the range shrinks to −31 to 31.

            Sign extension. To widen a two’s complement number (for example from 4 bits to 8 bits), copy the sign bit into the new places on the left. −5 in 4 bits is 1011; in 8 bits it is 1111 1011. Check with place values: 1011 = −8 + 2 + 1 = −5, and 1111 1011 = −128 + 64 + 32 + 16 + 8 + 2 + 1 = −5, the same value. +5 is 0101 in 4 bits and becomes 0000 0101 in 8 bits. If you padded a negative number with 0s instead, 1011 would become 0000 1011 = +11, which is a different number. Always copy the sign, not a fixed 0.

            Part 5: Subtraction by addition

            A processor does not need a separate subtractor circuit. To work out A − B it adds A to the two’s complement of B: A − B = A + (−B). Any carry out of the leftmost column is simply thrown away. That is the same discard you already used when you negated zero: the extra 1 walked off the left-hand end and the remaining bits were the answer.

            Worked example 3 (4 bits): 7 − 5. 5 = 0101, so −5 = flip 1010, then add 1 to get 1011.

            Carry   1 1 1 1
                      0 1 1 1     (7)
                    + 1 0 1 1     (−5)
                      -------
                    1 0 0 1 0
            Discard the carry out: 0010 = 2  ✔

            The carry out is 1, and throwing it away is the right thing to do: the true answer, 2, fits in 4-bit two’s complement (−8 to 7). A carry out is not, by itself, a sign that something has gone wrong. You will need a different test for overflow, in a moment.

            Worked example 4 (8 bits): 45 − 100. 100 = 0110 0100, so −100 = flip 1001 1011, then add 1 to get 1001 1100.

            Carry    0111 1000
                     0010 1101     (45)
                   + 1001 1100     (−100)
                     ---------
                     1100 1001
            = −128 + 64 + 8 + 1 = −55  ✔

            There is no carry out this time, and the answer −55 is inside the 8-bit range, so the result is correct. Check in decimal: 45 − 100 = −55. A second check is to add the result 1100 1001 back to 0110 0100 (that is, add 100) and confirm you recover 0010 1101 = 45, discarding any carry.

            Signed overflow

            If the true mathematical answer is outside the range the bits can hold, the 8-bit pattern you are left with is wrong. That event is called signed overflow. In two’s complement the detection rule is about signs, not about the carry out:

            • Overflow can only happen when you add two numbers with the same sign (two positives, or two negatives). Adding a positive to a negative always gives a result that sits between them, so it cannot leave the range if both inputs fitted.
            • It has happened if the result has the opposite sign: two positives give a negative pattern, or two negatives give a positive pattern.
            • The carry out of the leftmost column does not tell you about signed overflow. (It does for unsigned numbers, as in Adding Binary Numbers: Carries, Adders and Overflow.) Worked example 3 had a carry out and was fine; Worked example 5 below has no carry out and overflows.

            Worked example 5: 100 + 50 in 8 bits. This is the same as 100 − (−50). 0110 0100 + 0011 0010 = 1001 0110. Two positives produced a pattern whose sign bit is 1: it reads as −128 + 16 + 4 + 2 = −106. The true answer, 150, is bigger than 127, so this is overflow. The wheel picture is the same idea: starting at 100 and stepping 50 places clockwise takes you past 127 and around to the negative side.

            Worked example 6: −100 + (−60). −100 is 1001 1100 and −60 is 1100 0100. Adding them gives 1 0110 0000. Discard the carry out and you are left with 0110 0000 = +96. Two negatives gave a positive, and the true answer, −160, is below −128, so this overflowed too. Notice that a carry out of 1 was discarded, and the result was still wrong. Carry and signed overflow are different flags.

            Try it 2Subtract by adding

            Type A and B (−128 to 127) and tap Work it out. The steps show how an 8-bit processor works out A − B as A + (−B). The number line marks the 8-bit result; if the true answer is off the scale, that is overflow. Or tap an example.

            
            

            Part 6: Signed numbers in C

            In C, signed char is (on almost every computer) an 8-bit two’s complement number, so it holds −128 to 127. short is usually 16 bits (−32,768 to 32,767) and int is usually 32 bits, both two’s complement. This program prints the bits that are actually stored for a few values. It reads the same 8 bits as an unsigned char so that it can use / and % to pick out each bit without the sign getting in the way of the arithmetic.

            #include <stdio.h>
            
            /* Print the 8 bits stored for a signed
               char, using / and % on the bit
               pattern read as unsigned. */
            void show(signed char v)
            {
                unsigned char u = (unsigned char)v;
                int place = 128;
            
                printf("%5d = ", v);
                while (place > 0) {
                    printf("%d", (u / place) % 2);
                    if (place == 16)
                        printf(" ");
                    place = place / 2;
                }
                printf("\n");
            }
            
            int main(void)
            {
                show(5);
                show(-5);
                show(-1);
                show(127);
                show(-128);
                return 0;
            }
            

            Output:

                5 = 0000 0101
               -5 = 1111 1011
               -1 = 1111 1111
              127 = 0111 1111
             -128 = 1000 0000

            Compare −5 with the table in Part 3: 1111 1011 is flip-and-add-1 of 0000 0101, and the place values are −128 + 64 + 32 + 16 + 8 + 2 + 1 = −5. −1 is all 1s (a useful pattern to remember), and −128 is a 1 followed by seven 0s, just as Part 4 predicted. Positive 5 and 127 print with a leading 0, as every positive two’s complement number must.

            The next program does Worked example 5 in C. It also stores 200 (an unsigned value) in a signed char: the bits 1100 1000 do not change, but they are now read with the −128 column, so 200 − 256 = −56.

            #include <stdio.h>
            
            int main(void)
            {
                signed char a = 100;
                signed char b = 50;
                signed char sum = a + b; /* 150 */
                int full = a + b;
                unsigned char u = 200;
                signed char s = u;  /* same 8 bits */
            
                printf("int total:      %d\n", full);
                printf("in signed char: %d\n", sum);
                printf("200 read as signed: %d\n", s);
                return 0;
            }
            

            Output:

            int total:      150
            in signed char: -106
            200 read as signed: -56

            C works out a + b as an int, so full is a correct 150. Squeezing 150 into a signed char keeps only the 8-bit pattern 1001 0110, which reads as −106. Warning: the C standard leaves this conversion up to the compiler (gcc and most others behave as shown), and if a calculation on int itself overflows, the behaviour is undefined. Choose a type that is wide enough for your values.

            Try it 3Signed numbers drill

            Choose a type of question. Give bit patterns as all 8 bits (spaces are ignored). For negative decimal answers, type a minus sign.

            Summary

            SchemeNegative numbersZeros8-bit range
            Sign and magnitudeSet the leftmost bit to 1; the other bits hold the size.Two (+0, −0)−127 to 127
            Ones’ complementFlip every bit of the positive number.Two−127 to 127
            Two’s complementFlip every bit, then add 1. Leftmost column worth −128.One−128 to 127
            • Subtraction: A − B = A + (two’s complement of B); throw away the carry out.
            • Signed overflow: two numbers of the same sign give a result of the other sign.
            • C’s signed types use two’s complement; signed char is −128 to 127.
            • The pattern 1000 0000 is −128 in two’s complement, and it has no positive partner in 8 bits.

            Practice questions

            1. Write −60 in 8-bit sign and magnitude, ones’ complement and two’s complement.

            Show answer

            60 = 0011 1100. Sign and magnitude: 1011 1100. Ones’ complement: 1100 0011. Two’s complement: 1100 0100.

            2. The pattern 1110 1010 holds an 8-bit two’s complement number. What is it in decimal?

            Show answer

            −128 + 64 + 32 + 8 + 2 = −22.

            3. The pattern 1000 0001 is read in each of the three signed schemes. Give its value in each.

            Show answer

            Sign and magnitude: −1. Ones’ complement: flip → 0111 1110 = 126, so −126. Two’s complement: −128 + 1 = −127.

            4. State the range of 6-bit two’s complement numbers and 6-bit sign and magnitude numbers.

            Show answer

            Two’s complement: −32 to 31. Sign and magnitude: −31 to 31.

            5. Use 8-bit two’s complement to work out 30 − 70. Show the working.

            Show answer

            70 = 0100 0110, so −70 = 1011 1001 + 1 = 1011 1010. 0001 1110 + 1011 1010 = 1101 1000 = −128 + 64 + 16 + 8 = −40. ✔

            6. Add −100 and −60 in 8-bit two’s complement. Explain what goes wrong.

            Show answer

            −100 = 1001 1100 and −60 = 1100 0100. The sum is 1 0110 0000; discarding the carry leaves 0110 0000 = +96. Two negatives gave a positive, so the addition overflowed: the true answer, −160, is below −128.

            7. Give two reasons why two’s complement is preferred to sign and magnitude.

            Show answer

            It has only one zero, and normal binary addition gives correct results for negative numbers, so one adder circuit handles addition and subtraction. (It also gains one extra negative value.)

            8. Widen the 4-bit two’s complement number 1010 to 8 bits, and state its decimal value in both widths.

            Show answer

            Copy the sign bit: 1111 1010. 1010 = −8 + 2 = −6, and 1111 1010 = −128 + 64 + 32 + 16 + 8 + 2 = −6.

            Homework

            1. Make a table of all 16 four-bit patterns, with their values as unsigned, sign and magnitude, ones’ complement and two’s complement. Check some rows with Try it 1 (use the right-hand four bits and imagine the sign bit, or set the eight bits with four leading 0s or 1s by sign extension).
            2. Work out these in 8-bit two’s complement, showing every step and saying whether each overflows: 90 − 35, 35 − 90, 90 + 60, −90 − 60. Confirm the overflow cases on the number line in Try it 2.
            3. On the wheel in Try it 1, start at 127 and tap +1, then start at −128 and tap −1. Write one sentence that explains both wraps.
            4. Change patterns.c so it prints the pattern of every value from −8 to 7. Can you see the pattern from Part 4?
            5. Read Binary Manipulation on this site and try its examples.

            Mastery quiz: Signed Integers

            This 10-question quiz is separate from the short Quick quiz at the end of the lesson. Score 8/10 or higher to earn this lesson’s badge. Your best score is saved in this browser on this device.

            Mastery quiz: Signed Integers

            Your course badges: loading saved progress…

            View badges

              No course badges earned yet. Score 8/10 in a lesson quiz to earn its badge.

              Saved in this browser on this device. Clearing browser data may remove your badges.

              Answer all 10 questions. Earn this lesson’s badge at 8/10 or higher. Read the explanations, revisit the Try it activities and retry as often as you need. These are self-study badges, not formal grades.

              1. In 8-bit sign and magnitude, what is 1000 0111?
              2. How do you form the two’s complement of a binary number?
              3. What is the range of 8-bit two’s complement numbers?
              4. What is 1000 0000 in 8-bit two’s complement?
              5. What is the range of 4-bit two’s complement numbers?
              6. Which schemes have two different patterns for zero?
              7. In 8-bit two’s complement, 0101 0000 + 0100 0000 = 1001 0000. What has happened?
              8. A processor works out 9 − 4 using two’s complement. What does it actually do?
              9. To widen 1011 (4-bit two’s complement) to 8 bits you should write...
              10. In C, what range does a signed char usually hold?

              Exam tips

              Specimen Unit 1 Paper 01 (2021), Items 1 and 2. Two multiple-choice items: one gives an 8-bit pattern to be read in sign and magnitude, and the other asks how a value is stored using two’s complement in 8 bits. Write the place values (with −128 for two’s complement) before you look at the options.

              2024 Unit 1 Paper 02, Question 2. Later parts ask for the range of an 8-bit signed magnitude number and for a negative number written in two’s complement using 8 bits. The method is exactly Part 3; see my worked solution 2024 U1 Q2.

              2009 Unit 1 Paper 02, Question 1. Includes the range of numbers a small number of bits can represent and a short two’s complement conversion. Worked solution: 2009 U1 Q1.

              General advice: always state how many bits you are using and write all of them, including leading 0s and 1s; show flip and add 1 as two separate lines; check a negative answer by adding the place values (−128 + ...); and for signed overflow, talk about the signs, not the carry. More worked answers are on the CS Solutions page.

              Previous: Adding Binary Numbers: Carries, Adders and Overflow. Next: Fixed-Point and Floating-Point Numbers. See also: Binary Manipulation and Solution to the largest and smallest two’s complement numbers using 4 bits.

              Syllabus link: CAPE Computer Science (CXC A19/U2/21), Unit 1, Module 1: Computer Architecture. Specific Objective 4: explain how data is represented in the computer (fixed point: signed magnitude, ones’ complement, two’s complement).

              Video search terms

              Search YouTube for: "two’s complement explained", "sign and magnitude vs two’s complement", "binary subtraction using two’s complement", "signed overflow detection".

              Try it 4Quick quiz

              Tap an answer. All eight questions are self-checks on this lesson.

              Updates

              2026/11/24

              - Rebuilt the lesson with fuller explanations, diagrams and new Try it simulations.

              2026/11/23

              - Removed the Print this lesson button.

              - Published.

              2026/11/11

              - Draft written (local file, not yet on the site).

              © 2026 Vedesh Kungebeharry. All rights reserved.

              Number Bases: Binary, Octal and Hexadecimal

              A computer stores everything (numbers, text, pictures, programs) as patterns of bits. To read and write those patterns you need to count in base 2 (binary). Programmers also use base 16 (hexadecimal) and sometimes base 8 (octal), because they are short ways of writing long binary numbers. In this lesson you will convert between all four bases by hand, with a live place-value diagram and a stepper that shows every remainder, and you will see how C prints and reads numbers in each base.

              What you will learn

              • The units of data: bit, nibble, byte and word, and the 2n rule for how many patterns n bits can hold.
              • How place value works in base 10, base 2, base 8 and base 16, with A to F as the hex digits 10 to 15.
              • How to convert binary to decimal by adding place values, and decimal to binary (or hex, or octal) by repeated division, reading remainders from the bottom up.
              • How to convert between binary, hexadecimal and octal by grouping bits (fours for hex, threes for octal).
              • How C writes numbers in other bases with 0x, %x and %o, and the octal trap of a leading 0.

              Part 1: Bits, nibbles, bytes and words

              UnitSizeNotes
              Bit1 binary digitShort for binary digit. Holds 0 or 1.
              Nibble4 bitsOne hexadecimal digit. 16 possible patterns.
              Byte8 bitsThe smallest unit most memory can address. 256 patterns, so one byte can hold an unsigned number from 0 to 255.
              WordDepends on the processorThe number of bits the processor handles in one go, usually 32 or 64 today. See Memory Types and Features.

              With n bits there are 2n different patterns. So 4 bits give 16 patterns, 8 bits give 256, and 10 bits give 1024. This rule comes up again in every data-representation lesson that follows.

              Part 2: Place value in any base

              In base 10, each column is worth 10 times the column to its right: units, tens, hundreds. In base b, each column is worth b times the column to its right, and the digits go from 0 up to b − 1. Hex needs six extra digits for the values 10 to 15, so it uses letters: A = 10, B = 11, C = 12, D = 13, E = 14 and F = 15. When a number could be read in more than one base, write the base as a subscript, for example 1012 = 510, or 1F16 = 3110.

              BaseNameDigitsColumn values (right to left)
              2Binary0, 11, 2, 4, 8, 16, 32, 64, 128, …
              8Octal0 to 71, 8, 64, 512, …
              10Decimal0 to 91, 10, 100, 1000, …
              16Hexadecimal (hex)0 to 9, then A to F1, 16, 256, 4096, …
              DecimalBinary (4 bits)HexOctal
              0000000
              1000111
              2001022
              3001133
              4010044
              5010155
              6011066
              7011177
              81000810
              91001911
              101010A12
              111011B13
              121100C14
              131101D15
              141110E16
              151111F17

              Worked example 1: binary to decimal with place values

              Convert 0101 10102 to decimal. Write the place values above the eight bits, from the left: 128, 64, 32, 16, 8, 4, 2, 1. The bits are 0 1 0 1 1 0 1 0, so you add the columns that hold a 1: 64 + 16 + 8 + 2 = 90. Always write the place values down; an examiner can then award method marks even if the addition slips.

              A second check: 1011 01102 is 128 + 32 + 16 + 4 + 2 = 182. You will see this byte in the Try it below.

              Worked example 2: a hex number in decimal

              Convert 2A16 to decimal. The right-hand digit is the units, and A is 10, so that column is 10. The next digit to the left is worth 16: 2 × 16 = 32. The total is 32 + 10 = 42. In the same way, B616 is 11 × 16 + 6 = 176 + 6 = 182, which matches the binary total in Worked example 1’s second check.

              Tap the bits in the diagram. Each column shows its place value times the bit that sits in it. Columns that hold a 1 light orange and are added into the running total, which is also written as hex and as octal.

              Try it 1Place-value byte

              Tap a bit to flip it. Each column is worth twice the column to its right, starting from 1 on the right. Orange columns hold a 1 and are added to the decimal total. The caption also groups the bits for hex and octal.

              Bits (128s on the left, 1s on the right)

              Part 3: Decimal to binary, hex or octal, one step at a time

              To convert a decimal number into another base, divide by that base and keep the remainder, then divide the quotient again, until the quotient is 0. The first remainder is the rightmost digit (the units). The last remainder, when the quotient has just become 0, is the leftmost digit. That is why you read the remainder column from the bottom up.

              Worked example 3: 77 in binary

              Divide 77 by 2, again and again:

              1. 77 ÷ 2 = 38 remainder 1
              2. 38 ÷ 2 = 19 remainder 0
              3. 19 ÷ 2 = 9 remainder 1
              4. 9 ÷ 2 = 4 remainder 1
              5. 4 ÷ 2 = 2 remainder 0
              6. 2 ÷ 2 = 1 remainder 0
              7. 1 ÷ 2 = 0 remainder 1

              Read the remainders from the bottom up: 10011012. Check by place values: 64 + 8 + 4 + 1 = 77. The first remainder was 1 because 77 is odd; that first remainder is always the units bit.

              Worked example 4: 200 in hexadecimal

              Now divide by 16, because we want hex. 200 ÷ 16 = 12 remainder 8. Then 12 ÷ 16 = 0 remainder 12, and 12 is the digit C. Read from the bottom up: C816. Check: 12 × 16 + 8 = 192 + 8 = 200. The same method with 8 in place of 16 would give the octal form.

              Type a whole number, choose a base, and press Next step. Each row is one division. When the quotient reaches 0, the stepper reads the remainders from the bottom up and writes the answer. The box only accepts values from 0 to 65535, which is enough for 16-bit unsigned numbers.

              Try it 2Repeated-division stepper

              Enter a whole number, choose the base, then tap Next step to see one division at a time, or Show all to finish. The first remainder is the units digit; the last remainder is the left-hand digit.

              A second method for decimal to binary, which some students prefer, is to subtract the largest place value that fits, then the next, and so on. For 77 the largest power of two that fits is 64; the leftover is 13; 8 fits, leftover 5; 4 fits, leftover 1; 1 fits. The powers you used get a 1, the others a 0, so 1001101 again. Use whichever method you can do cleanly under exam pressure, and always convert back to check. The stepper shows the division method because it generalises immediately to hex and octal: you only change the number you divide by.

              Part 4: Grouping bits, and the same work in C

              Because 16 = 24, each hex digit stands for exactly four bits (one nibble). To convert binary to hex, start at the right, group the bits in fours (pad the left with zeros if the last group is short), and replace each group by its hex digit from the table in Part 2. 1111 0011 becomes F3. To go the other way, replace each hex digit by its four bits: 2A is 0010 1010.

              Octal uses groups of three bits, because 8 = 23. Group from the right: 10 110 1102 is 2668. This grouping is much faster than going via decimal when you already have the bits, and it is the method to use in an exam unless the question asks you to show place values.

              Worked example 5: grouping 1111 0011

              The left nibble 1111 is 8+4+2+1 = 15, which is F. The right nibble 0011 is 2+1 = 3. So the hex form is F3. Check via decimal: 128+64+32+16+2+1 = 243, and F316 is 15 × 16 + 3 = 240 + 3 = 243. For octal, group 11 110 011 (pad a zero on the left to make 011 110 011): 3, 6, 3, so 3638. Check: 3 × 64 + 6 × 8 + 3 = 192 + 48 + 3 = 243.

              C can print the same numbers for you. %o prints octal, %x or %X prints hex (small or capital letters), and a value written in the source as 0x6D is hex, while a value that merely starts with 0 is octal. That last point is a trap: 010 is not ten, it is 8. The second program prints 010 as 8, so you can see the trap rather than only being told about it.

              #include <stdio.h>
              
              /* Print n in base 2, using the
                 divide-by-2 method from Part 3. */
              void print_binary(int n)
              {
                  int bits[16];
                  int count = 0;
              
                  if (n == 0) {
                      printf("0");
                      return;
                  }
                  while (n > 0) {
                      bits[count] = n % 2; /* remainder */
                      n = n / 2;           /* quotient */
                      count++;
                  }
                  /* read the remainders bottom up */
                  while (count > 0) {
                      count--;
                      printf("%d", bits[count]);
                  }
              }
              
              int main(void)
              {
                  int nums[4] = {109, 255, 4096, 7};
                  int i;
              
                  for (i = 0; i < 4; i++) {
                      printf("%d: octal %o, hex %X\n",
                             nums[i], nums[i], nums[i]);
                      printf("  binary ");
                      print_binary(nums[i]);
                      printf("\n");
                  }
                  return 0;
              }
              

              Output:

              109: octal 155, hex 6D
                binary 1101101
              255: octal 377, hex FF
                binary 11111111
              4096: octal 10000, hex 1000
                binary 1000000000000
              7: octal 7, hex 7
                binary 111
              #include <stdio.h>
              
              int main(void)
              {
                  int a = 0x6D;   /* hex: starts 0x  */
                  int b = 0155;   /* octal: starts 0 */
                  int c = 109;    /* decimal         */
                  int d = 010;    /* a trap: octal!  */
              
                  printf("%d %d %d\n", a, b, c);
                  printf("010 is really %d\n", d);
                  printf("%x %X %#x %o\n", c, c, c, c);
                  return 0;
              }
              

              Output:

              109 109 109
              010 is really 8
              6d 6D 0x6d 155

              Try it 3Number-base drill

              Write place values first. The first remainder in repeated division is the units digit. Group binary in fours for hex and in threes for octal. In C, a leading 0 means octal.

              Summary

              • n bits give 2n patterns. A nibble is 4 bits (one hex digit); a byte is 8 bits (0 to 255 unsigned).
              • Place value in base b uses powers of b. Hex digits A to F stand for 10 to 15.
              • Binary to decimal: add the place values of the 1s. Decimal to another base: divide by the base, remainders bottom-up, first remainder on the right.
              • Binary to hex: group in fours from the right. Binary to octal: group in threes from the right. Always check by converting back.
              • In C, 0x starts a hex literal and a leading 0 starts an octal literal. %x and %o print those bases.

              Practice questions

              1. How many bits are in a nibble, and how many different patterns can it hold?

              Show answer

              4 bits, and 24 = 16 patterns, which is why one nibble is one hex digit.

              2. Convert 0101 10102 to decimal. Show the place values you used.

              Show answer

              Place values 128 64 32 16 8 4 2 1 under bits 0 1 0 1 1 0 1 0. Add 64 + 16 + 8 + 2 = 90.

              3. When converting decimal to binary by repeated division, which remainder is the units bit, and why?

              Show answer

              The first remainder. It is the leftover after dividing by 2, so it tells you whether the original number is odd or even, which is the 1s column.

              4. Convert 77 to binary by repeated division, and check by adding place values.

              Show answer

              Remainders bottom-up give 10011012. Check: 64 + 8 + 4 + 1 = 77.

              5. Convert 1111 00112 to hexadecimal by grouping, and check via decimal.

              Show answer

              1111 = F and 0011 = 3, so F3. Decimal 243, and 15 × 16 + 3 = 243.

              6. What is 2A16 in decimal? What is 20010 in hex?

              Show answer

              2A = 2 × 16 + 10 = 42. 200 ÷ 16 gives remainders 8 then C, so C816.

              7. How many bits does one octal digit stand for, and why?

              Show answer

              3 bits, because 8 = 23. Each octal digit is a group of three bits.

              8. In C, what does printf("%d", 012); print, and why?

              Show answer

              It prints 10. A leading 0 means octal, and 1 × 8 + 2 = 10.

              Homework

              • On paper, write the place values above 1011 0110 and convert it to decimal, hex and octal. Check your three answers against Try it 1.
              • Use the stepper to convert 109 to binary, octal and hex. Then confirm the printout of bases.c for 109.
              • Group 0110 1101 in fours and in threes (pad the left if needed) and write the hex and octal forms.
              • Predict what printf("%d", 010); prints, then run literals.c and explain the trap in one sentence.

              Mastery quiz: Number Bases

              This 10-question quiz is separate from the short Quick quiz at the end of the lesson. Score 8/10 or higher to earn this lesson’s badge. Your best score is saved in this browser on this device.

              Mastery quiz: Number Bases: Binary, Octal and Hexadecimal

              Your course badges: loading saved progress…

              View badges

                No course badges earned yet. Score 8/10 in a lesson quiz to earn its badge.

                Saved in this browser on this device. Clearing browser data may remove your badges.

                Answer all 10 questions. Earn this lesson’s badge at 8/10 or higher. Read the explanations, revisit the Try it activities and retry as often as you need. These are self-study badges, not formal grades.

                1. How many bits are in a nibble?
                2. What is 0101 1010 in decimal?
                3. When converting decimal to binary by repeated division, the first remainder you get is...
                4. What is 1111 0011 in hexadecimal?
                5. What is the hex number 2A in decimal?
                6. How many bits does one octal digit stand for?
                7. How many different patterns can 10 bits hold?
                8. In C, what does printf("%d", 012); print?
                9. 77 in binary, read from repeated division, is...
                10. 200 in hexadecimal is...

                Exam tips

                2009 Unit 1 Paper 02, Question 1. Includes a short binary-to-decimal conversion as part of a longer question on gates and binary arithmetic. Show the place values above the bits so the examiner can see your method. Worked solution: 2009 U1 Q1.

                Specimen Unit 1 Paper 01 (2021), Items 1 and 2, and 2024 Unit 1 Paper 02, Question 2. These move on to signed numbers, but every one of them starts by converting between decimal and binary, so this lesson’s methods must be automatic. See 2024 U1 Q2.

                Hex and octal. Number bases are named in Specific Objective 4. In the papers I have checked (the specimen papers and the solutions on this site) the questions use binary and decimal, but a hex or octal conversion is fair game, so practise with Try it 3.

                General advice: write the place values first; give binary answers with the number of bits the question asks for (keep leading zeros); group binary in fours; and always check by converting back. More worked answers are on the CS Solutions page.

                Previous: Logic Gates and Truth Tables. Next: Adding Binary Numbers: Carries, Adders and Overflow (lesson 07). See also: Decimal to binary, Binary Manipulation and int vs float: Truncation, Binary, and Choosing the Right Specifier.

                Syllabus link: CAPE Computer Science (CXC A19/U2/21), Unit 1, Module 1: Computer Architecture. Specific Objective 4: explain how data is represented in the computer (bits; bytes; number bases).

                Video search terms

                Search YouTube for: "binary to decimal conversion", "decimal to binary repeated division", "binary to hexadecimal grouping", "hexadecimal explained for beginners".

                Try it 4Quick quiz

                Tap an answer. All eight questions are self-checks on this lesson.

                Updates

                2026/11/24

                - Rebuilt the lesson with fuller explanations, diagrams and new Try it simulations.

                2026/11/23

                - Removed the Print this lesson button.

                - Reworded some sentences so they speak directly to students.

                - Published.

                2026/11/11

                - Draft written (local file, not yet on the site).

                © 2026 Vedesh Kungebeharry. All rights reserved.

                Logic Gates and Truth Tables

                Every part of a computer, from the adder in the processor to the cells in memory, is built from tiny switches called logic gates. A gate takes one or two bits in and gives one bit out, following a fixed rule. In this lesson you will learn the seven gates named in the CAPE syllabus, how to write their rules as truth tables and Boolean expressions, and how to work out what a circuit of several gates does. Every gate is also written as a line of C, so you can test your tables on a computer.

                What you will learn

                • What a truth table is, how many rows it needs and how to order the rows.
                • The symbol, rule, expression and truth table of NOT, AND, OR, NAND, NOR, XOR and XNOR (which the syllabus calls XAND).
                • How to complete the truth table of a circuit made from several gates, using working columns.
                • How to write the Boolean expression for a circuit, and how to build a circuit from a truth table.
                • Why NAND and NOR are called universal gates.
                • How C writes the same rules with &&, ||, ! and !=.

                Part 1: Bits, switches and truth tables

                Inside a chip, a bit is a voltage on a wire: a high voltage stands for 1 (true, on) and a low voltage stands for 0 (false, off). A logic gate is a small circuit of transistors that looks at its input wires and sets its output wire to 1 or 0.

                A truth table lists every possible combination of inputs and the output for each one. Each input can only be 0 or 1, so:

                • 1 input needs 2 rows; 2 inputs need 4 rows; 3 inputs need 8 rows.
                • In general, n inputs need 2n rows.
                • Write the rows in order by counting in binary: 000, 001, 010, 011, 100, 101, 110, 111. The rightmost input column alternates 0, 1, 0, 1; the next column goes 0, 0, 1, 1; the leftmost goes four 0s then four 1s. This way you never miss or repeat a row.

                Part 2: The seven gates

                The table below shows each gate with its standard (American) symbol, its rule in words and its Boolean expression. A small circle (a “bubble”) on a symbol’s output means NOT: it flips the result. CAPE accepts the usual notations: AND as A·B or A ∧ B, OR as A + B or A ∨ B, and NOT as A′, Ā or ∼A. The syllabus’s logic-symbols page uses ∧, ∨ and ∼.

                GateSymbolRuleExpression
                NOTNOT gate symbolOutput is the opposite of the input. Also called an inverter.X = Ā (NOT A)
                ANDAND gate symbolOutput is 1 only when all inputs are 1.X = A·B
                OROR gate symbolOutput is 1 when at least one input is 1.X = A + B
                NANDNAND gate symbolNOT AND. Output is 0 only when all inputs are 1.X = NOT (A·B)
                NORNOR gate symbolNOT OR. Output is 1 only when all inputs are 0.X = NOT (A + B)
                XORXOR gate symbolExclusive OR. Output is 1 when the two inputs are different.X = A ⊕ B
                XNORXNOR gate symbolEquivalence. Output is 1 when the two inputs are the same.X = NOT (A ⊕ B)

                Here are all the two-input truth tables side by side. Learn them as patterns of the output column, read from the top row (00) to the bottom row (11):

                ABANDORNANDNORXORXNOR
                00001101
                01011010
                10011010
                11110001
                • AND is 0001: a single 1 at the bottom. OR is 0111: a single 0 at the top.
                • NAND (1110) and NOR (1000) are AND and OR with every output flipped.
                • XOR (0110) is 1 in the middle two rows, where the inputs differ. XNOR (1001) is its opposite.

                A note on “XAND”. The syllabus list of gates includes XAND. That name is not standard in electronics. It is normally taken to mean the gate that gives 1 when both inputs are the same, which most books call XNOR or the equivalence gate. Learn it as XNOR, and recognise both names in a question. If a question ever defines XAND differently, follow the question’s definition.

                Try it 1Gate explorer

                Choose a gate, then tap A and B to switch them between 0 and 1. The output and the matching row of the truth table (highlighted) change straight away.

                Output X

                Part 3: Circuits of several gates

                Real circuits join gates together: the output of one gate becomes the input of another. To find what a circuit does, add working columns to the truth table, one for each gate output inside the circuit, and fill them in from the inputs towards the final output.

                Worked example 1: X = (A AND B) OR (NOT C)

                There are three inputs, so the table needs 23 = 8 rows. First fill in A·B (1 only in the rows where A and B are both 1). Then fill in NOT C (the opposite of the C column). Finally OR the two working columns together.

                ABCA·BNOT CX
                000011
                001000
                010011
                011000
                100011
                101000
                110111
                111101

                Read the result back in words: X is 1 whenever C is 0, and also when A and B are both 1. Writing a sentence like this is a good way to check a table.

                From a circuit diagram to an expression

                Start at the inputs and label the output wire of every gate with what it calculates. Work forward until you reach the final output. For example, if A and B go into a NOR gate, and its output goes into an AND gate together with C, label the NOR output NOT (A + B), so the final output is X = NOT (A + B) · C. Use brackets so the order is clear: NOT is done first, then AND, then OR, unless brackets say otherwise (just as × comes before + in arithmetic).

                From a truth table to a circuit

                To design a circuit, look at the rows where the output is 1. Write one AND term for each such row, using NOT on any input that is 0 in that row, then OR all the terms together. This is called the sum of products form.

                Worked example 2. XOR is 1 in two rows: A = 0, B = 1 and A = 1, B = 0. The terms are (NOT A)·B and A·(NOT B), so XOR = (NOT A · B) + (A · NOT B). That is an XOR gate built from two NOT gates, two AND gates and one OR gate. You can check it in Try it 2 (choose the third expression).

                Try it 2Fill in the truth table

                Choose an expression. Tap each ? in the X column to set it to 1 or 0, then tap Check. Stuck? Show the working columns.

                Part 4: NAND and NOR, the universal gates

                NAND and NOR are called universal gates, because any circuit at all can be built using only NAND gates (or only NOR gates). Chip makers like this: a whole chip can be made from one kind of gate. Three facts are enough to show it for NAND:

                • NOT from NAND: join both inputs together. A NAND A = NOT A.
                • AND from NAND: a NAND followed by a NAND-as-NOT. NOT (A NAND B) = A·B.
                • OR from NAND: invert each input first, then NAND them. (NOT A) NAND (NOT B) = A + B. (This is one of De Morgan’s laws.)

                Check the first fact with the NAND truth table: in the rows where A and B are equal (00 and 11), the output is 1 and 0, the opposite of A.

                Part 5: Logic gates in C

                C has no separate type for true and false. It uses whole numbers: 0 means false and any other value means true. The logical operators always give 0 or 1, so they behave exactly like gates. (Review Variables, format specifiers and printf if printf and %d are new to you.)

                GateC expressionNotes
                ANDa && bLogical AND
                ORa || bLogical OR
                NOT!aLogical NOT
                NAND!(a && b)NOT applied to AND
                NOR!(a || b)NOT applied to OR
                XORa != bTrue when the bits differ (for values 0 and 1)
                XNORa == bTrue when the bits are the same

                This program prints the two-input truth tables. Each pass of the inner loop is one row.

                #include <stdio.h>
                
                /* Truth tables for six gates.
                   In C, 0 means false and 1 means true. */
                int main(void)
                {
                    int a, b;
                
                    printf("A B | AND OR NAND");
                    printf(" NOR XOR XNOR\n");
                    for (a = 0; a <= 1; a++) {
                        for (b = 0; b <= 1; b++) {
                            int and_ = a && b;
                            int or_ = a || b;
                            int xor_ = (a != b);
                            printf("%d %d |", a, b);
                            printf("  %d   %d", and_, or_);
                            printf("   %d ", !and_);
                            printf("   %d", !or_);
                            printf("   %d", xor_);
                            printf("   %d\n", !xor_);
                        }
                    }
                    return 0;
                }
                

                Output:

                A B | AND OR NAND NOR XOR XNOR
                0 0 |  0   0   1    1   0   1
                0 1 |  0   1   1    0   1   0
                1 0 |  0   1   1    0   1   0
                1 1 |  1   1   0    0   0   1

                The output matches the table in Part 2. The next program works out Worked example 1. Instead of three nested loops it counts a row number r from 0 to 7 and takes A, B and C from the bits of r: A = r / 4, B = (r / 2) % 2 and C = r % 2. This is the same "count in binary" rule you use to write the rows by hand.

                #include <stdio.h>
                
                /* X = (A AND B) OR (NOT C)
                   Row r counts 0 to 7 in binary, so
                   A, B and C are the bits of r. */
                int main(void)
                {
                    int r;
                
                    printf("A B C | A.B NOT C | X\n");
                    for (r = 0; r < 8; r++) {
                        int a = r / 4;
                        int b = (r / 2) % 2;
                        int c = r % 2;
                        int p = a && b;  /* middle */
                        int q = !c;      /* middle */
                        int x = p || q;
                        printf("%d %d %d |", a, b, c);
                        printf("  %d    %d  ", p, q);
                        printf(" | %d\n", x);
                    }
                    return 0;
                }
                

                Output:

                A B C | A.B NOT C | X
                0 0 0 |  0    1   | 1
                0 0 1 |  0    0   | 0
                0 1 0 |  0    1   | 1
                0 1 1 |  0    0   | 0
                1 0 0 |  0    1   | 1
                1 0 1 |  0    0   | 0
                1 1 0 |  1    1   | 1
                1 1 1 |  1    0   | 1

                Try this: change the line int x = p || q; so the program prints the table for X = NOT (A + B) · C, then check it with Try it 2. C also has bitwise operators (&, |, ^ and ~) that apply a gate to every bit of a number at once. You will meet them when we look at registers.

                Try it 3Gate drill

                Name the gate from its output column, or work out an expression for given inputs. Answers are 0 or 1 for the expression questions.

                Summary

                IdeaKey points
                Truth tableLists every input combination: n inputs need 2n rows. Order the rows by counting in binary.
                AND, OR, NOTAND: 1 only if all inputs are 1. OR: 1 if any input is 1. NOT: flips the bit.
                NAND, NORAND and OR followed by NOT. Universal gates: any circuit can be built from either one alone.
                XOR, XNORXOR: 1 when the inputs differ. XNOR (the syllabus’s XAND, equivalence): 1 when they are the same.
                CircuitsAdd a working column for each gate. Work from the inputs to the output.
                DesignSum of products: one AND term per row with output 1, then OR the terms.
                In C&&, ||, !, != and == act as gates on 0 and 1.

                Practice questions

                1. How many rows does the truth table of a circuit with 4 inputs need?

                Show answer

                24 = 16 rows.

                2. Give the output column of a NOR gate for the rows 00, 01, 10, 11.

                Show answer

                1, 0, 0, 0. NOR is 1 only when both inputs are 0.

                3. A and B go into an AND gate. A and B also go into a NOR gate. The two outputs go into an OR gate. Write the expression and the truth table. What single gate does it match?

                Show answer

                X = A·B + NOT (A + B). Rows 00, 01, 10, 11 give 1, 0, 0, 1. It matches XNOR: the output is 1 when the inputs are the same.

                4. Complete the truth table for X = NOT A · (B + C). For which input rows is X = 1?

                Show answer

                X = 1 only when A = 0 and at least one of B, C is 1: rows 001, 010 and 011.

                5. Show how to make a NOT gate using one NOR gate.

                Show answer

                Join both inputs of the NOR gate to A. Then X = NOT (A + A) = NOT A: when A = 0 the output is 1, and when A = 1 it is 0.

                6. A circuit must give 1 only when exactly one of A and B is 1. Write a sum of products expression for it and name the gate.

                Show answer

                X = (NOT A · B) + (A · NOT B). It is XOR.

                7. In C, what does printf("%d", !(1 || 0)); print, and which gate is this?

                Show answer

                0. 1 || 0 is 1, and ! flips it to 0. NOT applied to OR is a NOR gate.

                Homework

                1. Draw the symbols for all seven gates from memory, then write the output column of each one under it. Check yourself against Part 2.
                2. Make up your own 3-input circuit with three gates. Draw it, write its expression and complete its truth table with working columns. Then change the circuit.c program to print the same table and compare.
                3. Using only NAND gates, draw circuits for NOT, AND and OR. Check each one with a truth table.
                4. For the expression X = (A + B) · NOT C, write a sentence in plain English that describes when X is 1 (for example, as a rule for when an alarm should ring).

                Exam tips

                Specimen Unit 1 Paper 01 (2021), Item 9. A multiple-choice item that shows four truth tables and asks which one belongs to a NAND gate. Know the output column 1, 1, 1, 0 by heart.

                Specimen Unit 1 Paper 01 (2021), Item 3. Shows a small circuit and asks which Boolean expression it implements. Label each gate’s output wire, as in Part 3, before you look at the options.

                Specimen Unit 1 Paper 02 (2021), Question 1(b). Asks you to construct the truth table for a circuit made of several basic gates. Show your working columns: they earn method marks even if the final column has a slip.

                2009 Unit 1 Paper 02, Question 1. Early parts ask for the truth tables of basic gates and for an XOR gate built from AND, OR and NOT gates, which is exactly Worked example 2. See my worked solution: 2009 U1 Q1.

                2024 Unit 1 Paper 02, Question 2. Begins with a circuit whose truth table turns out to match a single gate. Completing the table and then naming the gate is a common two-step pattern. See 2024 U1 Q2.

                More worked answers are on the CS Solutions page. General advice: always order your rows by counting in binary, write the number of rows (2n) before you start, and use brackets in expressions.

                Previous: Power Protection and Types of Computers. Next: Number Bases: Binary, Octal and Hexadecimal. See also: Logic Gates – Formal Introduction (an older introduction on this site).

                Syllabus link: CAPE Computer Science (CXC A19/U2/21), Unit 1, Module 1: Computer Architecture. Specific Objective 2: describe the basic building blocks of a computer (truth tables; logic gates AND, OR, NOT, NAND, NOR, XOR, XAND). Specific Objective 3: interpret the interaction among the basic building blocks (logic gates).

                Video search terms

                Search YouTube for: "logic gates truth tables explained", "NAND universal gate", "sum of products from truth table", "logic circuit to Boolean expression".

                Try it 4Quick quiz

                Tap an answer. All eight questions are self-checks on this lesson.

                Attributions to media used in this post:

                • Gate symbols (AND, OR, NOT, NAND, NOR, XOR, XNOR, ANSI style): jjbeard, public domain, via Wikimedia Commons (File:AND ANSI.svg, File:OR ANSI.svg, File:NOT ANSI.svg, File:NAND ANSI.svg, File:NOR ANSI.svg, File:XOR ANSI.svg, File:XNOR ANSI.svg).

                Updates

                2026/11/23

                - Removed the Print this lesson button.

                - Published.

                2026/11/11

                - Draft written (local file, not yet on the site).

                © 2026 Vedesh Kungebeharry. All rights reserved.

                Social Studies Revision: Special Days and Festivals – Infants 2

                This is extra Social Studies revision for Infants 2, for children about 6 or 7 years old. It is about special days and festivals we celebrate in Trinidad and Tobago. Read each part with a grown-up. Then try the picture quiz and the quick quiz. There is a worksheet to print at the end.

                If you hear no sound, check the volume, or try Chrome or Safari.

                Special days through the year

                Here are some special days, in order through the year. Find them on a calendar!

                • 8 September: Literacy Day
                • 5 October: World Teachers’ Day
                • Before Divali: Ramleela
                • October or November: Divali
                • 1 November: All Saints’ Day
                • 2 November: All Souls’ Day
                • 20 November: Universal Children’s Day
                • 25 December: Christmas Day
                • A different date each year: Eid-ul-Fitr

                Part 1: Literacy Day

                Literacy Day is on the 8th of September every year. To be literate means you are able to read and write.

                A tall stack of colourful books

                Why should we read?

                We read to have fun. We read to exercise our mind. We read to learn new things. We read because we can!

                Photo: Alexander Grey, CC0, via Wikimedia Commons

                Part 2: World Teachers’ Day

                World Teachers’ Day is on the 5th of October, all over the world.

                Thank you, teacher!

                It is a day to honour teachers for their special work. Teachers help us learn and grow.

                Say thank you

                You can make a card or say thank you to your teacher.

                Part 3: Ramleela

                Ramleela is celebrated by Hindus. It is a story that is acted out like a play, in the open, often on a savannah. Members of the Hindu community take part.

                The story

                The story tells how Sita, the wife of Lord Rama, was saved from Raavan, the demon king. Good wins over evil.

                Three tall, colourful figures of Raavan and his brothers

                Ten nights

                The play goes on for about ten nights, in the weeks before Divali. At the end, a big figure of Raavan is burnt.

                Photo: Tanuj_handa, CC0, via Wikimedia Commons

                Part 4: Divali

                Divali means festival of lights. It is celebrated by Hindus on the darkest night of the Hindu month of Kartik, in October or November.

                Clean and decorate

                Hindus clean and decorate their homes and yards.

                Pray

                Many fast and pray to Mother Lakshmi, the goddess of light. They do a pooja (a prayer).

                A lit clay deya

                Light deyas

                In the evening, they light deyas (small clay lamps). Light wins over darkness, and good wins over evil.

                Photo: Slyronit, CC BY-SA 4.0, via Wikimedia Commons

                Share food

                Families cook and share vegetarian food and sweets, like kurma and barfi.

                Stay safe: let a grown-up light the deyas, and keep away from flames.

                Part 5: All Saints’ Day and All Souls’ Day

                These are two holy days for Roman Catholics and some other Christians.

                All Saints’ Day: 1 November

                A day to honour the saints, holy people who are now in heaven. Many people visit the graves of loved ones who have died.

                Many candles glowing on graves in the evening

                All Souls’ Day: 2 November

                A day to pray for loved ones who have died. Many families go to the cemetery to light candles on the graves. Some people light candles at home.

                Photo: Marek Ślusarczyk (Tupungato), CC BY 3.0, via Wikimedia Commons

                Part 6: Universal Children’s Day

                Universal Children’s Day is on the 20th of November, all over the world. It reminds us that every child has rights.

                A name

                The right to a name.

                A family

                The right to a family.

                Love

                The right to be loved.

                Health care

                The right to health care, like a doctor or a nurse.

                Education

                The right to go to school and learn.

                Part 7: Christmas

                Christmas Day is on the 25th of December. Christians celebrate the birth of Jesus Christ. They go to church to pray.

                Trees and lights

                Families put up Christmas trees, lights and decorations.

                A glass of dark red sorrel drink

                Food and drinks

                We eat ham, fruit cake and pastelles. We drink sorrel and ginger beer.

                Photo: stu_spivack, CC BY-SA 2.0, via Wikimedia Commons

                Music

                We sing Christmas carols and enjoy parang.

                Giving

                We give gifts to family and friends, and help people in need. Christmas is a time for giving, sharing, loving and caring.

                Feliz Navidad means Merry Christmas in Spanish.

                Part 8: Eid-ul-Fitr

                Eid-ul-Fitr is celebrated by Muslims at the end of the month of fasting. Its date changes each year.

                A mosque with a green dome in south Trinidad

                Pray in a mosque

                Muslims pray in a mosque.

                Photo: Kalamazadkhan, CC BY-SA 3.0, via Wikimedia Commons

                Share and visit

                Families visit each other and share sweet sawine.

                Part 9: Who celebrates what?

                People of many religions live together in Trinidad and Tobago. We respect each other’s special days.

                Festival Who celebrates? What do they do?
                Christmas Christians Pray in a church
                Eid-ul-Fitr Muslims Pray in a mosque
                Divali Hindus Light deyas
                Ramleela Hindus Act out the story of Lord Rama

                Picture quiz

                The picture quiz needs JavaScript. Look back at the pictures above and name each one with a grown-up.

                Quick quiz

                Here is the Quick quiz without the games. Say your answer, then tap Show answer.

                1. Literacy Day is on …

                • a) 8 September
                • b) 5 October
                • c) 25 December
                Show answer

                Literacy Day is on the 8th of September.

                2. To be literate means you are able to …

                • a) read and write
                • b) swim
                • c) sing
                Show answer

                Literate means able to read and write.

                3. World Teachers’ Day is on …

                • a) 5 October
                • b) 20 November
                • c) 1 November
                Show answer

                World Teachers’ Day is on the 5th of October.

                4. Ramleela tells the story of …

                • a) Lord Rama and Sita
                • b) the scarlet ibis
                • c) the first President
                Show answer

                Lord Rama saves Sita from Raavan, the demon king.

                5. Divali means …

                • a) festival of lights
                • b) festival of food
                • c) festival of music
                Show answer

                Divali means festival of lights.

                6. All Saints’ Day is on …

                • a) 1 November
                • b) 2 November
                • c) 25 December
                Show answer

                All Saints’ Day is on the 1st of November. All Souls’ Day is the next day.

                7. On All Souls’ Day, many families …

                • a) light candles on the graves of loved ones
                • b) give out National Awards
                • c) fly kites
                Show answer

                They pray and light candles for loved ones who have died.

                8. Which is a right of every child?

                • a) the right to an education
                • b) the right to a car
                • c) the right to stay up late
                Show answer

                Every child has the right to go to school and learn.

                9. Christmas Day is on …

                • a) 25 December
                • b) 31 August
                • c) 8 September
                Show answer

                Christmas Day is on the 25th of December.

                10. Eid-ul-Fitr is celebrated by …

                • a) Muslims
                • b) Hindus
                • c) Christians
                Show answer

                Muslims celebrate Eid-ul-Fitr. They pray in a mosque.

                When JavaScript is off, use these questions and celebrate finishing together. Progress cannot be saved here.

                To print this worksheet, tap the button. To save it as a PDF instead, look in the print window for an option like Save as PDF, Save to PDF, Print to PDF or Download. The name is a little different on each phone, tablet and computer.

                Words to know

                Say these words with a grown-up. Can you use each one in a sentence?

                celebrate · festival · literate · teacher · Ramleela · Lord Rama · Sita · Raavan · Divali · deya · Mother Lakshmi · All Saints’ Day · All Souls’ Day · cemetery · rights · Christmas · parang · church · Eid-ul-Fitr · mosque

                Try it at home

                • Make a calendar of special days. Circle 8 September, 5 October, 1 and 2 November, 20 November and 25 December.
                • Make a thank-you card for your teacher.
                • Read a story with a grown-up every day.
                • Talk with your family about the special days you celebrate and the food you share.

                For parents and teachers

                This is extra Infants 2 Social Studies revision. After this post, your child should be able to:

                • give the dates of Literacy Day, World Teachers’ Day, All Saints’ Day, All Souls’ Day, Universal Children’s Day and Christmas Day
                • say what literate means and why we read
                • tell the Ramleela story in simple words
                • describe how Hindus celebrate Divali, how Christians celebrate Christmas and how Muslims celebrate Eid-ul-Fitr
                • name some rights of a child

                Festivals are described briefly and respectfully. Not every family marks every festival, and that is fine. Let children share how their own family celebrates.

                Ramleela is usually held over about ten nights in the weeks before Divali; dates vary by village. Divali and Eid-ul-Fitr move each year with the Hindu and Islamic calendars.

                Literacy Day, World Teachers’ Day, Ramleela, All Saints’ Day, All Souls’ Day and Universal Children’s Day go beyond our eight Infants 2 Social Studies lessons. They are included because many Infants 2 classes cover them.

                The photos of the Raavan figures and the grave candles were taken in other countries. Ramleela and All Souls’ Day in Trinidad and Tobago look a little different, so ask children what they have seen here.

                The read-aloud uses the device speech voice. Quiz scores and the badge stay in this browser only. No login.

                Back to Infants 2 Social Studies
                See all Revision Exercises →

                Image credits

                Photographs are from Wikimedia Commons and are shown here as links to the original files.

                • books: Stack of multicolored books on a table, Alexander Grey, CC0, via Wikimedia Commons
                • figures of Raavan: Ravana’s and his brothers’ effigies, Tanuj_handa, CC0, via Wikimedia Commons
                • a deya: An Earthen Lamp (Diya), Slyronit, CC BY-SA 4.0, via Wikimedia Commons
                • candles on graves: All Saints Day celebration – grave candles in the evening, Marek Ślusarczyk (Tupungato), CC BY 3.0, via Wikimedia Commons
                • sorrel: Homemade sorrel drink, stu_spivack, CC BY-SA 2.0, via Wikimedia Commons
                • a mosque: Hermitage Masjid, Hermitage Village, Trinidad and Tobago, Kalamazadkhan, CC BY-SA 3.0, via Wikimedia Commons

                Updates

                2026/11/19
                – Read aloud now pauses between lines.

                2026/11/18
                – First version of this extra Infants 2 Social Studies revision, with pictures, read-aloud, a picture quiz, a quick quiz and a worksheet.
                – Bigger pictures in the picture quiz, side by side on tablets and laptops.

                Social Studies Revision: Directions, Our Country and My School – Infants 2

                This is extra Social Studies revision for Infants 2, for children about 6 or 7 years old. Read each part with a grown-up. Look at the pictures. Then try the picture quiz and the quick quiz. There is a worksheet to print at the end.

                If you hear no sound, check the volume, or try Chrome or Safari.

                Part 1: Which way?

                Directions tell us where people and things are. Arrows can point four ways.

                up

                The arrow points up.

                down

                The arrow points down.

                left

                The arrow points left.

                right

                The arrow points right.

                A compass is a tool that shows directions. It helps us find places easily.

                Part 2: The four cardinal points

                The four main cardinal points are North, South, East and West. They help us find our way if we get lost. On a compass, North is at the top.

                N, S, E, W

                North is up. South is down. West is on the left. East is on the right.

                Say this poem with a grown-up:

                The sun rises in the East.
                The sun sets in the West.
                The sun does not really move: the Earth turns.
                When I face the East with my arms stretched out,
                my left arm points North,
                my right arm points South,
                and my back is to the West.

                Part 3: Where is it?

                Look at the map. The tree is in the middle.

                • The school is to the North of the tree.
                • The boy is to the South of the tree.
                • The house is to the West of the tree.
                • The bus is to the East of the tree.

                Part 4: Getting around

                Transport is how people and things move from place to place. We travel on land, on the sea and in the air.

                A white maxi-taxi with a green band

                land

                A maxi-taxi, a car and a bus go on land.

                Photo: Zagaboy, CC0, via Wikimedia Commons

                Two white ferries at the dock in Port of Spain

                sea

                A ferry, a boat and a ship go on the sea.

                Photo: Kalamazadkhan, CC BY-SA 4.0, via Wikimedia Commons

                An aeroplane flying in a blue sky

                air

                An aeroplane and a helicopter go in the air.

                Photo: BhuyanBhaskar, CC BY 4.0, via Wikimedia Commons

                Part 5: Independence Day

                The name of our country is the Republic of Trinidad and Tobago.

                31 August

                We celebrate Independence Day on the 31st of August every year. It is a national holiday.

                Parades

                Bands and groups march in parades.

                Fireworks

                We watch fireworks light up the sky at night.

                On 31 August we became independent. That means we make our own laws and choose our own leaders.

                Part 6: Republic Day

                We celebrate Republic Day on the 24th of September every year.

                24 September

                Republic Day is on the 24th of September.

                Our own President

                When we became a republic, our own President took the place of the Queen of England.

                The first President

                Our first President was Sir Ellis Clarke.

                National Awards

                National Awards are given out on Republic Day to people who have helped our country.

                Part 7: Our national emblems

                National emblems are special symbols of our country. They make us proud.

                The flag of Trinidad and Tobago: red, with a black band edged in white from corner to corner

                The national flag

                Our flag is red, white and black. Red is for the warm sun and our happy, lively people. White is for the sea and for all people being equal. Black stands for the earth and its riches, and the strength of our people.

                Photo: Wikimedia Commons contributors, Public domain, via Wikimedia Commons

                A bright red scarlet ibis wading in water

                Scarlet ibis

                The national bird of Trinidad. It is bright red. You can see it in the Caroni Swamp.

                Photo: Clément Bardot, CC BY-SA 4.0, via Wikimedia Commons

                A brown cocrico sitting on a branch in Tobago

                Cocrico

                The national bird of Tobago. It is brown. It is also called the Tobago pheasant.

                Photo: Francesco Veronesi from Italy, CC BY-SA 2.0, via Wikimedia Commons

                Bright red chaconia flowers

                Chaconia

                Our national flower. It is bright red and grows in the forest. It blooms around Independence time.

                Photo: Albert Sydney, CC BY-SA 3.0, via Wikimedia Commons

                A man playing two steelpans on a street in Trinidad

                Steelpan

                Our national instrument. It is made from an oil drum. It was invented in Laventille, Trinidad. Winston “Spree” Simon was the first person to play a tune on it.

                Photo: Shanel, CC BY-SA 3.0, via Wikimedia Commons

                The scarlet ibis and the cocrico are protected by law. Nobody is allowed to hunt them.

                Part 8: Our motto and watchwords

                Our national motto is: Together we aspire, together we achieve. It means that when we work together, we can reach our goals.

                Our national watchwords are three words to help us live well together.

                Discipline

                Good behaviour.

                Production

                To make or to create.

                Tolerance

                Acceptance: we accept and respect people who are different from us.

                Part 9: Budget Day

                A budget is a plan for how to spend and save money for a period of time.

                A family budget

                A family can plan what to buy and how much to save.

                The Red House in Port of Spain

                The National Budget

                The National Budget tells the country where the Government will get money and how it will spend it. The Minister of Finance reads it in Parliament, at the Red House.

                Photo: David Stanley, CC BY 3.0, via Wikimedia Commons

                Part 10: My awesome school

                La escuela means the school in Spanish.

                A good school is clean and beautiful. The children are kind, helpful and respectful. They have good manners and follow the rules.

                Listen

                I listen and follow instructions.

                Use good manners

                I always say please, thank you and excuse me.

                Tell the truth

                I always tell the truth.

                Walk, do not run

                I do not run or play rough in the classroom.

                Keep it clean

                I put all garbage in the bin and keep my books and classroom neat.

                Be kind

                We must be kind to each other.

                Picture quiz

                The picture quiz needs JavaScript. Look back at the pictures above and name each one with a grown-up.

                Quick quiz

                Here is the Quick quiz without the games. Say your answer, then tap Show answer.

                1. Independence Day is on …

                • a) 31 August
                • b) 24 September
                • c) 25 December
                Show answer

                Independence Day is on the 31st of August.

                2. Republic Day is on …

                • a) 24 September
                • b) 31 August
                • c) 1 November
                Show answer

                Republic Day is on the 24th of September.

                3. Who was our first President?

                • a) Sir Ellis Clarke
                • b) Winston Spree Simon
                • c) the Queen of England
                Show answer

                Sir Ellis Clarke was our first President.

                4. The sun rises in the …

                • a) East
                • b) West
                • c) North
                Show answer

                The sun rises in the East and sets in the West.

                5. I face the East and stretch out my arms. My left arm points …

                • a) North
                • b) South
                • c) West
                Show answer

                My left arm points North. My right arm points South.

                6. What are the colours of our flag?

                • a) red, white and black
                • b) red, yellow and green
                • c) blue, white and black
                Show answer

                Our flag is red, white and black.

                7. What does tolerance mean?

                • a) accepting others
                • b) making things
                • c) good behaviour
                Show answer

                Tolerance means accepting others.

                8. Who reads the National Budget?

                • a) the Minister of Finance
                • b) the President
                • c) the teacher
                Show answer

                The Minister of Finance reads the budget.

                9. A budget is a plan to …

                • a) spend and save money
                • b) play a game
                • c) sing a song
                Show answer

                A budget is a plan to spend and save money.

                10. True or false? We must put all garbage in bins.

                • a) True
                • b) False
                Show answer

                True. Garbage goes in the bin.

                When JavaScript is off, use these questions and celebrate finishing together. Progress cannot be saved here.

                To print this worksheet, tap the button. To save it as a PDF instead, look in the print window for an option like Save as PDF, Save to PDF, Print to PDF or Download. The name is a little different on each phone, tablet and computer.

                Words to know

                Say these words with a grown-up. Can you use each one in a sentence?

                directions · compass · North · South · East · West · transport · Independence · Republic · President · national emblem · motto · watchwords · discipline · production · tolerance · budget · Minister of Finance · manners · rules

                Try it at home

                • Stand outside in the morning and face the rising sun. That is East! Stretch out your arms: left is North, right is South, and your back is to the West.
                • Draw and colour our flag. Tell a grown-up what each colour stands for.
                • Find 31 August and 24 September on a calendar and circle them.
                • Talk about one school rule you keep every day.

                For parents and teachers

                This is extra Infants 2 Social Studies revision. After this post, your child should be able to:

                • say up, down, left and right, and name the four cardinal points
                • tell where a place is (north, south, east or west of something)
                • name land, sea and air transport
                • give the dates of Independence Day and Republic Day and how we celebrate them
                • name the national flag, birds, flower and instrument, the motto and the three watchwords
                • say what a budget is and who reads the National Budget
                • describe good manners and rules at school

                The flag meanings are given in simple words. Black stands for the earth and its riches, and the strength of our people, so a child who says “the earth” is right.

                The watchwords, Budget Day and the school rules go a little beyond our eight Infants 2 Social Studies lessons. They are included because many Infants 2 classes cover them.

                The names of the current Prime Minister, President and Minister of Finance change over time, so they are not included. You can add them together from today’s news.

                The read-aloud uses the device speech voice. Quiz scores and the badge stay in this browser only. No login.

                Back to Infants 2 Social Studies
                See all Revision Exercises →

                Image credits

                Photographs are from Wikimedia Commons and are shown here as links to the original files.

                • maxi-taxi: Maxitaxi new, Zagaboy, CC0, via Wikimedia Commons
                • ferry: Intra-island ferries – Trinidad, West Indies, Kalamazadkhan, CC BY-SA 4.0, via Wikimedia Commons
                • aeroplane: Flying Airplane in the Sky, BhuyanBhaskar, CC BY 4.0, via Wikimedia Commons
                • our national flag: Flag of Trinidad and Tobago, Wikimedia Commons contributors, Public domain, via Wikimedia Commons
                • scarlet ibis: Ibis rouge (Eudocimus ruber), Clément Bardot, CC BY-SA 4.0, via Wikimedia Commons
                • cocrico: Rufous-vented Chachalaca – Tobago, Francesco Veronesi from Italy, CC BY-SA 2.0, via Wikimedia Commons
                • chaconia: The Chaconia Flower, Trinidad (Warszewiczia coccinea), Albert Sydney, CC BY-SA 3.0, via Wikimedia Commons
                • steelpan: Pan player, Shanel, CC BY-SA 3.0, via Wikimedia Commons
                • the Red House: Red House of Trinidad and Tobago, David Stanley, CC BY 3.0, via Wikimedia Commons

                Updates

                2026/11/26
                – The compass now shows only the four main directions, like the Maps and the Four Directions note.
                – The map no longer shows diagonal arrows.
                – Read it to me no longer reads the picture words on the map.
                – Read it to me no longer reads the up, down, left and right titles on the arrow cards.

                2026/11/19
                – Read aloud now pauses between lines.

                2026/11/18
                – First version of this extra Infants 2 Social Studies revision, with pictures, read-aloud, a picture quiz, a quick quiz and a worksheet.
                – Black on the flag now stands for the earth and its riches, and the strength of our people.
                – Bigger pictures in the picture quiz, side by side on tablets and laptops.

                Healthy Habits and Safe Play – Infants 1 PE

                Being active keeps us healthy. Today we learn healthy habits for PE and how to play safely.

                School children in uniform playing with a skipping rope in a schoolyard
                Children skipping at break time. Playing is great exercise. Photo: Amuzujoe, CC BY-SA 4.0, via Wikimedia Commons.

                Healthy habits

                🍳 Eat breakfast before school.
                💧 Drink water at least three times a day: morning, at school and after play.
                😴 Sleep well at night.

                After play

                🧼 Wash your hands and face.
                💧 Drink water.
                🧘 Cool down: walk slowly and stretch.

                Clean water running from a kitchen tap
                Clean running water. Wash your hands with soap after play. Photo: Fourteenzerozero, CC0, via Wikimedia Commons.

                How do I feel?

                ❤️ My heart beats faster.
                😅 I feel hot and sweaty.
                😃 I feel happy and full of energy!
                😮‍💨 I breathe faster.

                These feelings are normal after exercise. Rest and drink water.

                Safe play

                👕 Wear loose, comfortable clothes and sneakers for PE.
                🪨 Look for hazards: broken glass, holes, sharp sticks, wet slippery floors.
                🙋 Tell an adult about any hazard.
                ☀️ Play in the shade on very hot days.

                Try it

                TRY ITHealthy and safe

                Pick a game. Then tap your answer.

                Let’s practise

                Point, say or draw. Open each answer after trying.

                1. Name three times you drink water each day.

                Show answer

                For example morning, at school, after play.

                2. What do you do after play?

                Show answer

                Wash hands and face, drink water, cool down.

                3. Name one hazard in a play area.

                Show answer

                For example broken glass, a hole, a wet floor.

                4. What do you wear for PE?
                (a) sneakers
                (b) slippers
                (c) party shoes

                Show answer

                (a) sneakers.

                Quick check

                Try these three on your own first. An adult may read the words.

                1. How often should you drink water?

                • At least three times a day
                • Once a week
                • Never
                Show answer

                At least three times a day. At least three times a day.

                2. What should you do after play?

                • Wash hands and face
                • Eat with dirty hands
                • Nothing
                Show answer

                Wash hands and face. Wash your hands and face.

                3. You see broken glass. What do you do?

                • Pick it up
                • Tell an adult
                • Step on it
                Show answer

                Tell an adult. Tell an adult. Do not touch it.

                When JavaScript is off, use these questions and celebrate finishing together. Progress cannot be saved here.

                My completion badge

                Help and retries are welcome. This badge celebrates finishing, not a test score. Discuss the answers, then save it.

                To print this worksheet, tap the button. To save it as a PDF instead, look in the print window for an option like Save as PDF, Save to PDF, Print to PDF or Download. The name is a little different on each phone, tablet and computer.

                PE lesson 3: Healthy Habits and Safe Play — worksheet

                Point, draw or tell an adult. An adult can write for you.

                1. Tick a box each time you drink water today: 💧 💧 💧.
                2. Draw yourself in the right clothes for PE.
                3. Draw a hazard and an adult fixing it.

                © 2026 Vedesh Kungebeharry. All rights reserved.

                PE words

                Say these words with an adult. Can you use each one in a sentence?

                healthy · water · breakfast · exercise · hazard · safe · sneakers · cool down

                Try it at home

                • Fill a water bottle each morning and check it is empty by evening.
                • Walk around a park together and spot hazards.
                • After play, make handwashing and a drink of water a routine.

                For parents and teachers

                After this lesson, your child should be able to:

                • describe healthy habits such as eating breakfast and drinking water at least three times a day
                • wash hands and face after play and say how their body feels after exercise
                • spot hazards in a play area and choose suitable clothes for PE

                Warm up first, use a clear, flat space (grass or a mat for rolls), and have an adult nearby. Children with health conditions should follow their doctor’s advice. Children with asthma or other conditions should keep their medicine handy and rest when needed.

                Accept pointing, speaking, signing or communication aids. An adult can scribe. Observe the hands-on work as well as the Quick check; the badge records supported completion only.

                Previous: Lesson 2: Walk, Run, Jump, Throw and Catch
                Next: All Infants 1 PE lessons
                Back to Infants 1 PE

                Updates

                2026/11/19
                – Changed a picture clue.
                – Read aloud now pauses between lines.

                2026/11/18
                – The Infants 1 page now remembers this lesson, so you can carry on where you left off.
                – First version of this lesson.

                Attributions to media used in this post:

                Children playing on skipping rope.jpg – Amuzujoe – CC BY-SA 4.0 (via Wikimedia Commons; image resized only)
                Water running from kitchen tap.jpg – Fourteenzerozero – CC0 (via Wikimedia Commons; image resized only)

                © 2026 Vedesh Kungebeharry. All rights reserved.