← IB Computer Science

A1.2 · Book pp. 24–66

Data representation and computer logic

Your level

Everything a computer stores comes down to 1s and 0s. This section shows how those bits become numbers, text, pictures and sound, and how simple gates make decisions with them.

What you need to know

All of A1.2 is for both SL and HL.

PointTopic
A1.2.1The main ways of representing data: binary and hexadecimal
A1.2.2How binary stores text, images, audio, video and numbers
A1.2.3The purpose and use of logic gates
A1.2.4Constructing and analysing truth tables
A1.2.5Constructing logic diagrams

Why binary won

Early machines tried other bases. Babbage’s Analytical Engine used decimal, and the Soviet Setun computer of 1958 used base 3. Binary won for three reasons:

  • Simple hardware: a transistor is a switch, and a switch has two states.
  • Reliability: with only two states, small changes in voltage (noise) rarely change a value.
  • Logic: Boolean algebra maps directly onto two-state circuits.

Next: number bases →

A1.2.1 Binary and hexadecimal

In any base, each place is worth the base times the place to its right. A bit is one binary digit, a nibble is 4 bits, and a byte is 8 bits.

1286432168421
00101011

00101011₂ = 32 + 8 + 2 + 1 = 43₁₀. Always write the place values down first.

⚠️ Common mistake

11111111₂ is 255, not 256. A byte has 256 possible values, but one of them is 0.

Every conversion

From → toMethodExample
Binary → decimalAdd the place values under each 1. Or double the running total and add the next bit, from the left.1101: 1, 3, 6, 13
Decimal → binaryDivide by 2 repeatedly. Read the remainders from last to first, because the first remainder is the rightmost bit.13: 1, 0, 1, 1 → 1101
Decimal → binaryOr subtract place values from 128 downwards, writing 1 when you can.58 = 32 + 16 + 8 + 2
Binary → hexSplit into nibbles and convert each one.0110 1011 → 6B
Hex → binaryTurn each digit into 4 bits.C5 → 1100 0101
Decimal → hexDivide by 16 repeatedly. Read the remainders from last to first.229: 5, 14 → E5
Hex → decimalMultiply each digit by its power of 16.3A = 3 × 16 + 10 = 58

Hex digits run 0–9, then A = 10 up to F = 15. Programmers use hex because each digit maps to exactly 4 bits, so it is a compact way to read binary in memory dumps, debugging tools and colour codes.

🔬 Lab: converter

Binary
Hexadecimal
Divide by 2

🎯 Practice: fresh questions every time

Prefixes

DecimalSizeBinarySize
Kilobyte (KB)1000 bytesKibibyte (KiB)1024 bytes
Megabyte (MB)1000 KBMebibyte (MiB)1024 KiB
Gigabyte (GB)1000 MBGibibyte (GiB)1024 MiB
Terabyte (TB)1000 GBTebibyte (TiB)1024 GiB
Petabyte (PB)1000 TBPebibyte (PiB)1024 TiB

The scale continues with exa and zetta. A lowercase b means bits and an uppercase B means bytes, so 100 MB/s is eight times faster than 100 Mb/s.

✍️ Programming exercise

Write an app that converts between binary, decimal and hexadecimal without using built-in conversion functions.

Python model answer
def to_binary(n):
    bits = ""
    while n > 0:
        bits = str(n % 2) + bits
        n = n // 2
    return bits.zfill(8)


def to_decimal(bits):
    total = 0
    for b in bits:
        total = total * 2 + int(b)
    return total


def to_hex(n):
    digits = "0123456789ABCDEF"
    out = ""
    while n > 0:
        out = digits[n % 16] + out
        n = n // 16
    return out or "0"


print(to_binary(42))            # 00101010
print(to_decimal("10111011"))   # 187
print(to_hex(254))              # FE

Next: text →

A1.2.2 Characters and strings

Text is stored by giving each character a number. Everyone must agree on the numbers, which is why encoding standards exist.

ASCII

ASCII was standardized in 1963 so that devices from different makers could exchange text. It began with 7 bits (128 characters). Extended ASCII uses 8 bits (256 characters), but countries filled the extra space differently, so documents did not always travel well.

The codes have a neat pattern. The first three bits show the case, and the last five give the position in the alphabet:

Starts withMeaningExample
011Lowercase01100001 = a
010Uppercase01000001 = A
00100000SpaceThe last five bits are all 0

🔬 Lab: text to binary

Binary:

Characters beyond ASCII show their UTF-8 bytes.

Unicode

The Unicode Consortium formed in 1991 to give every character in every language one unique number. Version 15.0 from 2022 has 149,186 characters, including Thai, Chinese and emoji. In Python, ord("A") returns 65 and ord("ก") returns 3585.

UTF-8UTF-16UTF-32
Bytes per character1–42 or 4Always 4
Key featureBackward compatible with ASCIIUses surrogate pairs outside the Basic Multilingual PlaneSimple to process
Used inThe web, most appsWindows, JavaRarely, because of its size

How UTF-8 marks its bytes

BytesPattern
10xxxxxxx
2110xxxxx 10xxxxxx
31110xxxx 10xxxxxx 10xxxxxx
411110xxx 10xxxxxx 10xxxxxx 10xxxxxx

The leading 1s say how many bytes belong to the character, and 10 marks a continuation byte. Remove the markers, join the x bits, and you have the code point. This keeps ASCII text at its original size. Its drawback is that variable-length characters take more processing than a fixed width.

✍️ Programming exercises

  1. Build a secret message app that turns text into binary and back, with the spaces removed.
  2. Write a Caesar cipher. Then add a decrypt function, and one that brute-forces the key.
Python: text and binary
def encode(text):
    return "".join(format(ord(c), "08b") for c in text)


def decode(bits):
    return "".join(chr(int(bits[i:i + 8], 2)) for i in range(0, len(bits), 8))


secret = encode("Meet at noon")
print(secret)
print(decode(secret))   # Meet at noon
Python: Caesar cipher
def shift(message, key):
    out = ""
    for ch in message:
        if ch.isalpha():
            base = ord("A") if ch.isupper() else ord("a")
            out += chr((ord(ch) - base + key) % 26 + base)
        else:
            out += ch
    return out


def decrypt(message, key):
    return shift(message, -key)


def brute_force(message):
    for key in range(1, 26):
        print(key, decrypt(message, key))


code = shift("Hello", 3)
print(code)              # Khoor
print(decrypt(code, 3))  # Hello
brute_force(code)        # the real word appears at key 3

Next: images, audio and video →

Images

A bitmap is a grid of pixels, each stored as a binary value. Two settings control its quality and its size:

ResolutionColour depth
MeaningNumber of pixels, width × heightBits per pixel
Too lowBlocky, pixelated imageBanding in smooth gradients
Raising itMore detail, larger file2depth colours, larger file

image size in bits = width × height × colour depth

Real files are larger because they hold metadata such as dimensions and colour depth. Sharpness also depends on pixels per inch: the same image looks clearer on a phone than on a cinema screen.

Most screens use 24-bit colour: one byte each for red, green and blue, which gives about 16.8 million colours. Each channel runs 0–255, so a colour can be written in hex. RGB (216, 190, 199) is #D8BEC7.

NamePixelsNamePixels
VGA640 × 480Quad HD2560 × 1440
HD1280 × 7204K3840 × 2160
Full HD1920 × 10808K7680 × 4320

🔬 Lab: draw a 1-bit bitmap

Click pixels. 1 is dark and 0 is light. This 8 × 8 image at 1 bit per pixel takes 64 bits, or 8 bytes.

Rows as hex:

Worked example with metadata

A 640 × 480 bitmap has 1024 colours, and metadata adds 20%.

  1. 1024 = 2¹⁰, so the depth is 10 bits.
  2. 640 × 480 × 10 = 3,072,000 bits = 384,000 bytes.
  3. 384,000 × 1.2 = 460,800 bytes = 460.8 KB.
Code: make a greyscale filter

This reads every pixel. Weighted averages match the way eyes respond more strongly to green. Try a small image first, then invent your own filter.

from PIL import Image        # pip install pillow

image = Image.open("photo.jpg").convert("RGB")
width, height = image.size
result = Image.new("RGB", (width, height))

for y in range(height):
    for x in range(width):
        r, g, b = image.getpixel((x, y))
        grey = int(0.3 * r + 0.59 * g + 0.11 * b)
        result.putpixel((x, y), (grey, grey, grey))

result.save("grey.jpg")

Audio

Sound is a continuous analogue wave. An analogue-to-digital converter samples its amplitude at regular intervals and stores each sample in binary.

Sample rateBit depthChannels
MeaningSamples per secondBits per sampleMono 1, stereo 2
CD quality44.1 kHz16-bit2
Professional48 kHz24-bit2

bits per second = sample rate × bit depth × channels

FormatType
WAV, AIFFUncompressed
FLACLossless
MP3Lossy

Video

A container format such as MP4, MKV or AVI holds frames, audio tracks, metadata and subtitles. Frames are still images shown at 24–60 per second, like a flipbook.

raw bits = width × height × colour depth × frames per second × seconds

Raw frames are far too large, so they are compressed. They are often converted from RGB to YUV, which keeps brightness separate from colour. Eyes are more sensitive to brightness, so colour detail can be reduced.

Spatial (intraframe)Temporal (interframe)
RemovesRedundancy inside one frameRedundancy between frames
MethodCompresses each frame like a photoPredicts frames and stores only the differences
Works best whenScenes change a lot from frame to frameMuch of the picture stays the same

🔬 Lab: storage calculator

Next: integers and reals →

Storing integers

SystemHow it works−5 or example8-bit rangeNote
UnsignedPlain binaryNot possible0 to 255Positive only
Two’s complementInvert the bits, add 111111011−128 to +127One zero, so it is the usual choice
One’s complementInvert the bits11111010−127 to +127Two zeros
Sign-magnitudeFirst bit is the sign10000101−127 to +127Two zeros
BCD4 bits for each decimal digit72 = 0111 0010Not a signed systemExact decimals, more bits, harder arithmetic
Gray codeNeighbours differ by one bit3 = 010Not a signed systemRotary encoders on robot arms
Excess-NAdd N before storingExcess-3: 2 → 0101Depends on NMakes signed values easy to sort

🔬 Lab: see a number in every system

Gray code for 0–7

Value01234567
Binary000001010011100101110111
Gray000001011010110111101100

Storing real numbers

Fixed point

The binary point stays in one agreed position. After the point, the places are worth ½, ¼, ⅛ and 1/16. With four bits on each side, 6.75 is 0110.1100. As a signed value this format runs from −8 to 7.9375 in steps of 0.0625. It is simple and fast, but its range is small.

Floating point (IEEE 754)

Floating point works like scientific notation in binary. Single precision uses 32 bits:

PartBitsJob
Sign10 positive, 1 negative
Exponent8Power of two, stored in Excess-127
Mantissa23Significant digits, without the leading 1
Worked example: −6.625
  1. In binary: 6.625 = 110.101.
  2. Normalize: 1.10101 × 2².
  3. Sign: 1, because it is negative.
  4. Exponent: 2 + 127 = 129 = 10000001.
  5. Mantissa: 10101 followed by eighteen 0s.

Result: 1 10000001 10101000000000000000000

Floating point covers a huge range, which is why science, engineering and graphics rely on it. It still cannot store every decimal exactly, so rounding errors happen, and it needs more complex hardware.

Next: logic gates →

A1.2.3 Logic gates

In the 1800s George Boole described logic as algebra. Claude Shannon later showed that it could design electrical circuits. Transistors, invented in 1947, made small gates possible, and they are the building blocks of every digital device.

A transistor is a switch: voltage on its control wire lets current flow between two electrodes. Join transistors in series and both must be on, which gives AND. Join them in parallel and either can be on, which gives OR.

The gates

NOT

Output is the opposite of the input. Written with a bar over A.

AX
01
10

AND

A · B. 1 only if both inputs are 1.

ABX
000
010
100
111

OR

A + B. 1 if at least one input is 1.

ABX
000
011
101
111

NAND

NOT (A · B). 1 unless both inputs are 1.

ABX
001
011
101
110

NOR

NOT (A + B). 1 only if both inputs are 0.

ABX
001
010
100
110

XOR

A ⊕ B. 1 if the inputs are different.

ABX
000
011
101
110

XNOR

NOT (A ⊕ B). 1 if the inputs are the same.

ABX
001
010
100
111

Original diagrams. In exams, write NOT as a bar over the term. A buffer gate simply outputs its input.

NAND is AND then NOT, NOR is OR then NOT, and XNOR is XOR then NOT.

Next: truth tables →

A1.2.4 Truth tables

From a circuit

  1. Count the inputs. n inputs give 2n rows.
  2. Fill the inputs: the right column alternates every row, the next every two rows, the next every four.
  3. Add a column for each intermediate point in the circuit.
  4. Work from left to right through the circuit, then fill in the output.

From a description

Find the inputs, then look for words that signal gates: “and”, “or”, “not”, “unless”.

Worked example: a sprinkler

A sprinkler runs when it is switched on (A) and either the soil is dry (B) or it is very hot (C).

Let P = B + C. Then X = A · P.

ABCPX
00000
00110
01010
01110
10000
10111
11011
11111

✍️ Your turn

Write the truth table and Boolean expression for each, then check it in the lab.

  1. A level crossing barrier lifts only if no train is detected (T) and the operator has not pressed stop (S).
  2. A greenhouse vent opens if it is hot (H) or humid (M), provided the system is enabled (E).
  3. A bank vault opens if the manager (M) and at least two of three staff (A, B, C) turn their keys.
Answers
  1. X = NOT T AND NOT S
  2. X = E AND (H OR M)
  3. X = M AND ((A AND B) OR (A AND C) OR (B AND C))

Order of operations

Brackets come first, then NOT, then AND and NAND, then OR, NOR and XOR.

🔬 Lab: truth table builder

Next: Karnaugh maps →

Karnaugh maps

A K-map lays out a truth table so that patterns show up. Simplifying an expression means fewer gates, which saves cost, space and power.

Grouping rules

  • Group only 1s, in sizes of 1, 2, 4 or 8.
  • Groups are rectangles. Diagonals are not allowed.
  • Make each group as large as possible, and use as few groups as you can.
  • Groups may overlap.
  • Groups may wrap around from the left edge to the right edge.

For each group, keep a variable only if it stays the same across the whole group. Join the groups with OR.

Worked example

Simplify NOT A · B · NOT C + NOT A · B · C + A · B · C.

C \ AB00011110
00100
10110
  1. The vertical pair in column 01: A = 0 and B = 1 stay fixed, C changes. This gives NOT A · B.
  2. The horizontal pair in row 1: B = 1 and C = 1 stay fixed, A changes. This gives B · C.

Answer: X = NOT A · B + B · C.

⚠️ Common mistake

The headings go 00, 01, 11, 10, in Gray code. If you use normal binary order, neighbouring cells can differ in two variables and the groups stop working.

🔬 Lab: see the K-map

Notice the 1s in the left and right columns. They wrap around to form one group of four.

✍️ Your turn

Draw the truth table and K-map, then simplify. Check your answer by typing both versions into the lab.

  1. A · B + A · NOT B + NOT A · B
  2. NOT B · C + A · NOT B · NOT C + A · NOT B · C
  3. A · B · C + A · B · NOT C + NOT A · NOT B · C + NOT A · B · C
Answers
  1. A + B
  2. NOT B · C + A · NOT B
  3. A · B + NOT A · C

Next: logic diagrams →

A1.2.5 Logic diagrams

To draw a circuit from an expression, work from the brackets outward, as you would in maths.

Example: Y = (A · B) + (NOT A · NOT B)

  1. Draw inputs A and B on the left.
  2. Connect A and B to an AND gate for the first bracket.
  3. Connect A to one NOT gate and B to another, then feed both into a second AND gate.
  4. Feed both AND outputs into an OR gate. Its output is Y.
ABY
Original diagram of an XNOR built from basic gates.

✍️ Your turn

Sketch each circuit on paper. Use the truth table lab to test the expression.

  1. Y = (A · B) ⊕ A
  2. Y = (A + B) · NOT (A · B)
  3. Y = A · B + C
  4. Y = (A ⊕ B) · (B ⊕ C)
  5. Y = NOT (A · B) · C + NOT (A + B)

Next: review →

Quick quiz

1. What is the largest value in 8-bit unsigned binary?
2. What is 2C in decimal?
3. An advert offers 200 Mb/s. What is that in megabytes per second?
4. How many bytes is 1 MiB?
5. Which Unicode encoding uses 1 to 4 bytes per character and stays compatible with ASCII?
6. How many colours does a 5-bit colour depth allow?
7. What is the 8-bit two’s complement form of −1?
8. Why might a clock display use BCD?
9. Which system is designed so neighbouring values differ by exactly one bit?
10. A · B + C has no brackets. What happens first?
11. How many rows does a truth table for 3 inputs have?
12. Why are K-map headings in Gray code order?

Exam-style questions

These are written for this site in the style of Paper 1. Answer on paper first, then open the mark points.

  1. Convert 11010110 to hexadecimal, showing your working. [2]

    Mark points
    • Split into nibbles: 1101 and 0110 [1].
    • 13 and 6, so D6 [1].
  2. Calculate the file size in kilobytes of a 640 × 480 bitmap with 1024 colours, ignoring metadata. [2]

    Mark points
    • 1024 colours need 10 bits per pixel [1].
    • 640 × 480 × 10 = 3,072,000 bits = 384,000 bytes = 384 KB [1].
  3. Calculate the storage in MB for one minute of 48 kHz, 24-bit stereo audio. [3]

    Mark points
    • 48,000 × 24 × 2 = 2,304,000 bits per second [1].
    • × 60 = 138,240,000 bits [1].
    • ÷ 8 = 17,280,000 bytes = 17.28 MB [1].
  4. Explain why UTF-8 is preferred to UTF-32 for web pages. [3]

    Mark points
    • UTF-8 uses a single byte for ASCII characters, while UTF-32 always uses four [1].
    • Pages are smaller, so they use less storage and transfer faster [1].
    • It stays backward compatible with existing ASCII text [1].
  5. Distinguish between spatial and temporal video compression. [2]

    Mark points
    • Spatial removes redundancy within a single frame [1].
    • Temporal removes redundancy between frames by storing only the differences [1].
  6. Represent −12 in 8-bit two’s complement, showing each step. [3]

    Mark points
    • +12 = 00001100 [1].
    • Invert: 11110011 [1].
    • Add 1: 11110100 [1].
  7. Outline one advantage and one disadvantage of floating point over fixed point. [2]

    Mark points
    • Advantage: represents a much larger range of values [1].
    • Disadvantage: arithmetic is more complex and slower, or some values have rounding errors [1].
  8. A greenhouse fan runs if the manual switch M is on, or if it is hot H and the door D is closed. Using D = 1 for open, write a Boolean expression and construct the truth table. [4]

    Mark points
    • X = M + (H · NOT D) [1].
    • Eight rows with all input combinations [1].
    • X = 1 on every row where M = 1 [1].
    • With M = 0, X = 1 only at H = 1, D = 0 [1].
  9. Use a Karnaugh map to simplify NOT A · B · NOT C + NOT A · B · C + A · B · C. [3]

    Mark points
    • Correct K-map with 1s at AB = 01 for C = 0 and C = 1, and AB = 11 for C = 1 [1].
    • Group of two gives NOT A · B [1].
    • Second group gives B · C, so X = NOT A · B + B · C [1].