And Computer Logic: Data Representation
And Computer Logic: Data Representation
SYLLABUS CONTENT
By the end of this chapter, you should be able to:
» A1.2.1 Describe the principal methods of representing data
A1.2.2 Explain how binary is used to store data
yvwy
A1 Computer fundamentals
turned on or off, aligning perfectly with the binary system'’s two-state logic. Additionally,
Boolean algebra, the mathematical framework for logical circuit design and operation, enables
straightforward implementation of complex operations using simple logic gates with binary
inputs: 1 (on / rue) or 0 (off / false).
The increased reliability of binary systems stems from their use of only two states. Small
variations in signal strength do not affect data integrity as much as in systems using larger
# Noise: unwanted bases, making binary more robust in noisy environments.
electrical disturbances As all data on a computer system is stored in binary, we need systems to represent numerous
that can affect the types of data, such as integers, strings, characters, images, audio and video, in binary form.
integrity of signals
being processed by a H Representation of integers in binary
computer; this noise is
To represent numbers in binary, it is useful to remember the basics of our decimal system
not related to sound,
but to variations in (base-10).
voltage or current In the decimal system, as we count, we start with a single digit and increment it by 1 until we
that can disrupt the reach 9. After 9, we introduce a new digit to the front to represent larger numbers. Let’s break
accurate transmission
down the decimal number 1024:
and processing of
digital data. 1000s 100s 10s 1s
0 1 1 0
1KiB= 1 MiB
= 1GiB= 1TiB= 1PiB= 1EB = 1ZiB=
1024 bytes 1024 KiB 1024 MiB 1024 GiB 1024 TiB 1024 PiB 1024 EiB
Kilobyte Megabyte Gigabyte Terabyte Petabyte Exabyte Zettabyte
KB MB GB TB PB EB ZB
Bits and byte notation are worth knowing when dealing with mobile-phone and internet companies.
ar
If the two advertisements above were from two different internet companies, assuming the
cost is the same, which one offers faster speeds and by how much?
(.-Top tip! 1 Starting from the right, assign the place values for each binary bit.
2 Sum each of the place values that has a 1 underneath it.
When converting to
and from binary, it is For example, to convert 10111011, to decimal:
always a good idea to 128 64 32 16 8 4 2 1
write the digit place
1 0 1 1 1 0 1 1
values down first.
Trying to remember
these in your head can 128+32+16+8+2+1=187
lead to silly mistakes. Doubling method:
128 64 32 1 Start with the leftmost bit (the most significant bit).
16 8 4 2 Double the current total and add the next bit.
2 1
3 Repeat until all bits are processed.
A1 Computer fundamentals
For example, to convert 10111011, to decimal:
Step Binary digit Current total Calculation
1 1 1 | Initial value
2 0 2| 1x2+0=2
3 1 5|/ 2x2+1=5
4 1 Mis5x2+1=1m
5 1 23 | NMx2+1=23
e 0 46 | 23x2+0=46
7 1 93 | 46x2+1=93
8 1 187 | 93 x2+1=187
(‘Common mistake
# Least significant bit If you use this method, remember to start with the most significant bit (MSB), not the least
(LSBY): the rightmost significant bit (LSB).
bit in a binary number,
representing the
smallest value position
(0 or1).
Convert the following binary (base-2) numbers to decimal (base-10):
4 Quotient: the result
obtained when one 1 11001010, 4 00011110,
number is divided by 2 01101101, 5 11100001,
another, e.g. in the 3 1011001,
division of 15 by 3, the
quotient is 5.
Converting decimal numbers to binary
There are two main methods for converting a decimal number to binary: the division method
and the subtraction method.
Division method:
1 Divide the decimal number by 2.
2 Write down the quotient and the remainder.
The remainder will be either 0 or 1. This represents a digit of the binary number (the LSB
on the first division).
3 Update the quotient.
4 Repeat until the quotient is 0.
5 Construct the binary number (this is read from the remainders from the first to the last).
Tor example, to convert 42, to binary:
(‘Common Division step Quotient Remainder
mistake 4272 21 0
Remember to 21/2 10 1
construct the 10/2 5 0
remainders in the
5/2 2 1
correct order to
format your binary 2/2 1 0
number. The first 1/2 ] 1
remainder is the least
significant bit (LSB).
Construct the binary number from the remainders and pad to 8-bits: 00101010,
32, is smaller, so we write a 1 below it and calculate the remainder from the subtraction, the
result of which will carry to the next place value:
1010 - 8m = 210
4, is larger than 2 so writea 0
2,,is equal, so calculate the remainder (0) and write a 1
128 64 32 16 8 4 2 1
0 0 1 0 1 0 1 0
A1 Computer fundamentals
B Representation of integers in hexadecimal
Hexadecimal (often abbreviated as hex) is a base-16 number system that uses 16 distinct
symbols to represent values, rather than the 10 of decimal or 2 of binary. The symbols
include the digits 0 to 9 and then the letters A to T, where A represents 10, B represents 11,
C represents 12, D represents 13, E represents 14 and F represents 15.
4 Debugging tools: Hexadecimal is used with computers for several reasons. The ease of conversion between
software applications binary and hexadecimal is straightforward because each hex digit maps directly to a 4-hit
or utilities used by binary sequence. For example, the binary number 1111 can be represented as F in hex.
developers to identify, Another reason is that it provides a more compact way to represent a binary value. This makes
analyse and fix bugs it much easier for us to read and communicate large binary numbers. This is why you often see
or issues within a
hex used in debugging tools, memory dumps and assembly language programming.
program by inspecting
code, variables and Converting binary numbers to hexadecimal
execution flow. Converting binary to hexadecimal is a straightforward calculation.
4 Memory dump: 1 Split the binary byte (8 bits) into two nibbles (2 x 4 bits).
a process where 2 Calculate the decimal value of these 4 bits.
the contents of a
3 Convert the decimal values into their hexadecimal equivalents and rejoin them.
computer's memory
are captured and For example, to convert 01101011, to hexadecimal:
saved, typically for the 1 Split the byte into 2 nibbles:
purpose of diagnosing 0110, 1011,
and debugging 2 Calculate the decimal value:
software issues.
6l[} 1110
# Nibble: 4 bits.
3 Convert both decimal values to their hexadecimal equivalents and rejoin them:
A1 Computer fundamentals
2 Multiply them by 16 raised to the power of its position index, starting from 0 on the right:
21x16'=2x16=32,
15x16°=15x1=15,
3 Sum the results:
32+415=47,,
Add hexadecimal conversion functionality to the binary converter app you created before.
ASCll encoding
The development of ASCII began in 1960 and was officially standardized in 1963. It was
developed because there was no standardized way to encode text characters, which led to
compatibility issues between devices and systems. Each manufacturer used its own proprietary
encoding system, which made it very difficult for devices to communicate with each other.
ASCII was designed to provide a common standard for the interchange of text data.
ASCII initially started out as a 7-bit encoding system, which gave it the ability to represent
128 (27) different characters, which was considered sufficient for most basic text data (letters,
numbers, punctuation and control characters). HHowever, as computing became more global
and applications required support for additional characters, an 8-bit extension to ASCII
was developed, giving it the ability to represent 256 (2%) characters. This was referred to as
extended ASCII, and the new characters were mainly used for Western European languages.
ASCII uses a simple but clever system to represent characters in binary (as long as we are
only considering the Latin (English) alphabet). The first five bits from the right are used to
represent the letter by its numerical place in the alphabet.
Tor example:
01100001, - 1, =
01100010, - 2, = b
01100011, - 3, = c
Create an application so that you can send secret messages to your friends.
Write an application that accepts either a string of characters or a stream of binary. It should
either encode the characters using ASCIl and binary or convert the binary back into text.
To make the binary less easy to decode by hand, you could remove all spacing between the
8-bit characters.
Unicode encoding
In the 1960s, the United States and the majority of English-speaking countries had a system
in 7-bit ASCII that worked for the English alphabet. Other non-English speaking countries
had their own unique encoding systems to work with their own languages. When the ASCII
system was increased to 8 bits (extended ASCII), allowing for 256 characters for use in
modern computers, countries did not agree on the same standard. Nordic countries started
using the extra space to encode characters for their own languages, and Japan used four
different systems that were not even compatible with each other. This was not a huge issue
as communication between these systems was rare, but then the internet was launched and
compatibility became very important as more and more information was being shared between
systems in different countries.
In 1991, the Unicode Consortium was created to try and solve this problem. The organization
was established to develop, maintain and promote the Unicode Standard, which provides a
unique number for every character, regardless of platform, program or language. It needed
to create a system that was capable of storing all the characters and punctuation marks from
all the languages in the world, but also wanted it to be backwards compatible with ASCIL At
the time of writing, the current Unicode Standard version 15.0, released in September 2022,
encodes 149,186 different characters. Unicode includes the Latin, Cyrillic, Greek and Arabic
alphabets, and Chinese characters, as well as many others, and also includes emojis and
mathematical and other technical symbols. In Unicode, each letter or symbol is assigned a
unique number, for example:
B A=65
m {L=27721
m & =128169
A1 Computer fundamentals
You can find the numerical representation for any character or symbol using the code below:
Python
# Python examples
char
a = 'A'
char_han = '{l"
char poo = '&'
# Get Unicode code points as integers
code_point_a = ord(char
a) # 65
code_point_
han ord(char_han) # 27721
code point poo ord(char poo) # 128169
# Print integer representations
print
(code point a) # Output: 65
print (code point_han) # Output: 27721
print (code point
poo} # Output: 128169
Java
public class UnicodeExample { H
HH
public static void main(Stringl[] args) ({ H
HH
// Define characters
H
char charA = 'A';
H
char charHan = 'i{';
String charPoo = "&"; // Note: Java uses UTF-16 and
// the emoji is usually a surrogate pair
// Get Unicode code points as integers
int codePointA = (int) chard; // 65
int codePointHan = (int) charHan; // 27721 H
int codePointPoo = charPoo.codePointiAt
(0); // 128169 1H
HH
// Print integer representations
System.out.println("Unicode code point of 'A': " +
codePointd); // Output: &5
System.out .println("Unicode code point of '{i': " +
codePointHan); // Output: 27721
System.out.println("Unicode code point of '&': " +
codePointPoo); // Output: 128169
HH
Haesessasessssiessatastasitatasanstassanantsnnn sesssssssessassessasesrsansarasnnranannnanns
Variable length | 1-4 bytes per character 2 or 4 bytes per character 4 bytes per character
encoeding
Note Compatibility: backward Surrogate pairs: for Simplicity: easier to process
# Basic Multilingual
compatible with ASCII characters outside the because each character is
Plane (BMP): the Basic Multilingual Plane exactly 4 bytes
maost commonly used (BMP), two 16-bit code
characters and symbals units are used
for almost all modern Usage Most commonly used Often used in Windows and | Less common due to higher
languages. encoding on the web and in | Java environments storage requirements
many applications
Let’s examine UTF-8, the most commonly used encoding system, and understand
its functionality.
Instead of merely expanding the size to accommodate over 100,000 characters, which would
have adversely impacted most online content, a more efficient solution was devised. Iad
all characters been standardized to use 32 bits, each letter in the ASCII system would have
quadrupled in size. This would have resulted in significantly larger documents and web pages,
leading to increased storage requirements and slower transfer times. The system also needed
never to send eight zeros (00000000) in a row, as many older systems would see this as the end
of communication and would stop listening.
So the UTT-8 system kept the ASCII system the same. The letter “A” is encoded as:
01000001 = A
However, if the character needed went beyond the standard ASCII system, “¢” for example,
more than one byte would be required:
11000011 10101001 = ¢
The bits in bold are important. The first three significant bits “110” on the first byte represent
that this character is made up of two bytes in total (a 0 is needed at the end to show when this
information is finished). The second byte starts “10”, which means this is a continuation. If
you remove those 53 bits and then put both bytes together:
00011101001 =233 =¢
Another example is:
11110000 10011111 10011000 10000100 = =
This emoji requires four bytes using the UTT-8 system. The first byte communicates that this
character is made up of four bytes (“11110”) and the next three bytes start with “10”, showing
they are continuation bytes. If we remove that information:
0001 1111 0110 0000 0100 = 128516 = &
UTF-8 has been adopted by the internet as the main character encoding system; however,
it doesn't come without some issues. Due to the variable length, some characters (especially
those from Asian languages or emojis) take more space compared to single-byte encodings.
This can lead to larger file sizes in certain contexts. The processing required to handle
variable-length encoding also requires more complex processing compared to fixed-length
systems such as UTF-32.
A1 Computer fundamentals
# Shift cipher: a type Despite these issues, UTF-8 has proved to be a versatile and effective encoding standard that
of substitution cipher, meets the needs of the modern internet. Its backward compatibility, efficiency and broad
where each letter in support make it an enduring choice for encoding text. While it does have some challenges,
the plaintext is shifted particularly with handling non-ASCII characters and variable-length encoding, these are not
a certain number of
significant enough ever to warrant a wholesale replacement. Therefore, it’s likely that UTF-8
positions down or up
will continue to be the dominant text encoding standard for the foreseeable furure.
the alphabet.
The code below uses a Caesar cipher to encrypt the string that is input using a key. A Caesar cipher is a simple shift cipher,
where each letter is considered to be an integer (a=1, b = 2, ¢ = 3, and so on) and the key is added to this to find the
encrypted letter, for example:
5tring input: "Hello”
Key input: 1
Output: fmmp
Python
def caesar cipher encrypt (message, key):
encrypted message = "'
for char in message:
if char.isalpha(): # Check whether the character is a letter
shift = ord("A") if char.isupper() else ord("a") # Determine the
# ASCII offset
# Shift the character and wrap around the alphabet if necessary
encrypted char = chr((ord(char) - shift + key) % 26 + shift)
encrypted message += encrypted char
else:
encrypted message += char # Non-letter characters remain unchanged
return encrypted message
# User input
message = input ("Enter the message to encrypt: ")
key = int(input ("Enter the key (an integer): "))
# Encrypt the message
encrypted message = caesar cipher encrypt(message, key)
print (f"Encrypted message: {encrypted message}")
1 return encryptedMessage.toString();
1 After studying how this code works, write the decrypt function for someone who receives an encrypted message.
2 Write a function that is able to brute force an encrypted message so you can identify the key used.
A1 Computer fundamentals
l Images
In 1957, Russel Kirch scanned an analogue photo of
his son Walden, converting the picture into a digital
file. This was the first ever digital image created. Tt
was a significant milestone in the evolution of visual
technology, revolutionizing the way we capture, store
and manipulate pictures. The development of early
digital cameras and scanners, which enabled devices to
convert light into digital data, started the trend that has
now become commonplace, and the transition from film
to digital has transformed numerous industries, from
photography and medical imaging to telecommunications
and entertainment.
Bitmap images
Bitmap images, also known as “raster” images, are one
of the most fundamental forms of digital graphics. They
reproduce images by using a grid of pixels, with each pixel
assigned a specific colour and intensity.
At the bottom of the page is a bitmap image with an image
resolution dimension of 13x10 (13 pixels wide by 10 pixels
high). Each pixel is “described” using 1 bit of data: either
1 or 0. In this case, 1 = black and 0 = white (a monochrome
image), and the amount of bits used to describe the colour
is known as the “bit depth” or colour depth. So, we have a
M The first ever digital image: Russel Kirch’'s son, Walden, in 1957 13x10 image with a 1-bit colour depth in this example.
To calculate the size of this image, the formula is:
# Analogue: a
continuous signal that image size = width (pixels) x height (pixels) x colour depth (bits per pixel)
represents varying 13 x 10 x 1 = 130 bits (or 130/ 8 = 16.25 bytes)
physical quantities, such
However, in reality, this calculation is not completely accurate, as the image would require
as sound waves, which
varies smoothly over a more data to store metadata and other header information. This could include information
range; digital represents such as dimensions, colour depth and other attributes that allow the CPU to read the image
data in discrete binary data accurately so it displays the image correctly to the screen.
values (0s and 1s),
enabling precise and oc|lo|lo|o|o|lo|lo|oOo|O|O|O|O]|O
error-resistant processing.
. 0 0 0 0 0 0 0 0 0 0 0
# Bitmap: a type of
digital image composed ololo olololo olololo
of a grid of pixels, each
holding a specific colour 0|0 00
value, representing the
" . 0 0 0 [4] o] 0
image in a rasterized
format. 0 0
# Pixel: short for “picture
element”; the smallest 0 0 ol meyo e 0 0
unit of a digital image or 0 0 olliie ITol o 1o o o
display, representing a
single point in the image olololo 0 olololo
with a specific colour
and intensity. olo|lo|lo|lo|o|lo|o|o|o|o|o]|oO
24 bit (true colour) 16.8 million Standard for most images and video, digital photography
30 bit (deep colour) Over 1 billion Professional photography, high-end monitors and televisions
36 bit Over 68 billion Medical imaging, professional graphics
A1 Computer fundamentals
G A+ " AT, A The majority of modern-day screens are 24 bit, allowing for
. 16.8 million colours. They have three lights per pixel: a red,
a green and a blue light, otherwise known as “RGB”, and
have a value range from 0 to 255 (1 byte per colour channel).
This is sufficient for most applications, as most human eyes
can only distinguish between around 10 million distinct
colours. Monitors that go beyond 24 bit are normally only
necessary in professional fields where precision is crucial.
On the left is a high-resolution image. If we zoom in to
the dress on this image, we can see the breakdown of the
individual pixels and the values of the distinct colour
channels. When working with graphics, these values are
often shown in hexadecimal. If we take the top left pixel of
the dress as an example:
—
R
G
[l
E= RS©
w
G
8
R
G
mowm so®m «
RGB Calculator
26
R 28
0
G im
19
L]
M The colour values for the top left pixel of the dress in the photo
— created using www.w3schools.com/
colors/colors_rgb.asp
M The same image using multiple colour depths: 24 bits to 0 bits - created using www.csfieldguide.org.nz/
enfinteractives/image-bit-comparer
1
A bitmap image uses a colour depth of 3 bits, allowing for eight distinct colours.
How many bits are needed to represent the colours if the bitmap image uses 32 distinct colours?
Raj is creating a bitmap graphic fora game. The image dimensions are 10 pixels wide and
12 pixels tall.
How many pixels are there in total in the image?
Alice is organizing her digital artwork collection that she has created over the years.
While transferring her artwork files to a new cloud storage service, she notices that each
file is larger than she anticipated. This is because, aside from the actual image data, the file
includes extra information necessary for accurate reproduction of the image. What is this
additional information, which contains details about the pixel data, called?
Determine the storage capacity needed for a bitmap image with dimensions of
800 x 600 pixels that supports 512 different colours.
Then, calculate the file size in kilobytes (kB) if the file metadata occupies an additional 25 per
cent of the space. Present your answer as a real number, including the decimal values.
A1 Computer fundamentals
Here are some fun ways to explore images in more depth using Python or Java.
1 Extract and print RGB values.
import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
public class ImageToRGB {
public static void main(String[] args) {
try {
// Load the image
BufferedImage image = ImagelIO.read(new File("sample image.jpg"));
// Get image dimensions
int width = image.getWidth();
int height = image.getHeight
() ;
// Loop through each pixel
for (int yv = 0; y < height; y++) {
for (int = = 0; x < width; x++) {
// Get the RGB wvalue of the pixel
int pixel = image.getRGB(x, y);
Color color = new Color(pixel);
// Extract the red, green and blue components
int red = color.getRed();
int green = color.getGreen();
int blue = color.getBlue();
// Print the RGB values
System.out.println("Pixel at (" + x + ", " + y + "}: R=" +
red + ", G=" + green + ", B=" + blue);
}
} catch (IOException e) {
e.printStackTrace()
;
pu——
T TT T T L L T LR T L T T T TT T TRT TP IPTN
Python
pip install pillow
Use this code to access the RGB values for each pixel
from PIL import Image
# Load the image
image = Image.open('sample image.jpg")
# Convert the image to RGB mode
image = image.convert ("RGE")
# Get the image dimensions
width, height = image.size
# Extract and print RGB wvalues
for y in range (height):
for x in range (width) :
pixel = image.getpixel
((x, y))
red, green, blue = pixel
print (f"Pixel at ({x}, {vy}): R={red}, G-{green}, B={blue}")
Python
from PIL import Image
# Load the image
image = Image.open("sample image.jpg")
# Convert the image to RGB mode
image = image.convert ('RGE')
# Get the image dimensions
width, height = image.size
# Create a new image to store the grayscale result
grayscale_image = Image.new("RGB", (width, height))
# Apply a grayscale filter
for y in range (height) :
for x in range (width) :
pixel = image.getpixel((x, y))
red, green, blue = pixel
grayscale = int (0.3 * red + 0.59 * green + 0.11 * blue)
grayscale image.putpixel((x, y), (grayscale, grayscale, grayscale))
# Save the grayscale image
grayscale_image.save('grayscale
image.jpg")
A1 Computer fundamentals
import java. awt .Color;
import java. awt .image.BufferedImage;
import java. io.File;
import java. io.I0OException;
import javax.imageio.ImagelO;
public class ImageToGrayScale {
public static void main(String[] args) {
: try {
// Load the image
BufferedImage image = ImagelIO.read(new File("sample image.jpg"));
// Get image dimensions
int width = image.getWidth();
int height = image.getHeight
() ;
// Create a new image to store the grayscale result
BufferedIimage grayscaleImage = new BufferedImage (width, height,
BufferedImage.TYPE INT RGB);
// RBpply a grayscale filter
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
// Get the RGB value of the pixel
int pixel = image.getRGB(x, ¥);
Color color = new Color (pixel);
// Extract the red, green and blue components
int red = color.getRed();
int green = color.getGreen();
int blue = color.getBlue();
// Compute the grayscale value
int grayscale = (int) (0.3 * red + 0.59 * green + 0.11 *
blue)
;
// Create a new Color object with the grayscale value
Color grayColor = new Color(grayscale, grayscale, grayscale);
// Set the new pixel value in the grayscale image
grayscalelmage.setRGB(x, y, grayColor.getRGB());
}
// Save the grayscale image
ImageIO.write (grayscaleImage, "jpg", new File("grayscale
image
java.jpg"));
} catch (IOException e) {
e_printStackTrace
() ;
——
:
HH
HH
H
3 After studying how the grayscale filter works, are you now able to create your own unique filters?
4 kHz (kilohertz): a A single second of a 44.1 kHz, 16-bit stereo (meaning two channels) audio has:
unit of frequency equal
B 44,100 samples per second
to 1000 cycles per
second, commonly used B cach sample represented by 16 bits
to measure the sampling m atotal storage need per second of 44,100 samples / second x 16 bits / sample x 2 channels =
rate of audio signals.
1,411,200 bits per second, or 176,400 bytes per second.
-1.0 {
T T T T T T
0.0 0.2 0.4 0.6 0.8 1.0
1.0 [ I —Analogue signal
-2 Digital signal
0.5
@
°3
=
[-%
0.0
E
<
—0.5
-1.0-
T T T T T T
0.0 0.2 0.4 0.6 0.8 1.0
Time (s)
M The blue continuous waveform represents an analogue signal, which is a smooth and continuous representation of sound. The
digital signal consists of discrete samples taken at regular intervals (sampling rate), illustrating how the continuous analogue signal is
converted into a series of discrete points in digital form.
Storage formats
There are many different types of file formats for storing audio. The most common are WAV,
AIFF, MP3 and FLAC. They mainly differ by whether they are compressed or uncompressed.
Uncompressed formats store the raw binary data, whereas compressed formats use algorithms
to reduce the file size for storage or transmission. Just like with image compression, audio
A1 Computer fundamentals
# Stereo: a method compression attempts to reduce the file size by removing parts of the audio signal that are
of sound reproduction less noticeable to human senses, in this case the ears. There are both lossy and lossless types
that uses two or more of compression used with audio. Lossless algorithms compress the data without any loss of
audio channels to create quality, whereas lossy algorithms permanently remove audio that is less noticeable to the
the perception of sound
human ear on the recording.
coming from different
directions, enhancing B WAV (Waveform Audio File Format): uncompressed
the sense of spatial AIFF (Audio Interchange File Format): uncompressed
depth and dimension.
MP3 (MPEG Audio Layer III): compressed (lossy)
1 What is the main difference between an analogue signal and a digital signal in the context
of audio?
2 What is the process of converting an analogue audio signal into a digital signal called, and
what does it involve?
3 Calculate the storage needed per minute for a 44.1 kHz, 16-bit stereo audio file.
4 Explain the difference between lossy and lossless audio compression and give an example
of each type of format.
Explore audio files further using the code below. This will allow you to analyse the amplitude of
any MP3 file.
You will need to install the following libraries:
B soundfile
H numpy
m matplotlib
B scipy.
Run this command in your terminal:
pip install soundfile numpy matplotlib scipy
1
Python 1
1
import soundfile as sf !
import numpy as np :
import matplotlib.pyplot as plt :
from scipy.fftpack import fft 1
# Load the audio file :
samples, sample rate = sf.read("name
of file. mp3") :
# If stereo, select one channel :
if samples.ndim > 1: :
samples = samples[:, 0] :
# Visualize the waveform :
plt.figure(figsize=(12, 6&)) :
plt.plot (samples) :
plt.title("Audio Waveform") :
M Video
Videos are made up of various components that are all contained within an encapsulated
container format such as MP4, MKV or AVIL. The components are:
frames (visual data)
audio tracks
metadata
subtitles and closed captions.
Audio is stored as described in the Audio section above,
and metadata and subtitles are stored as text, so this
section will focus only on how the video data is stored.
Video is essentially stored as a sequence of still images,
otherwise known as “frames”. When played in quick
succession (usually 24 to 60 frames per second), these
frames create the illusion of motion. This is very similar
to the technique you may have used to create a flipbook.
The frames are stored and encoded in binary format,
M Digital video playback is similar to a flipbook: a number of utilizing various techniques to optimize space and ensure
images that are shown quickly, creating the illusion of motion efficient playback.
Frames
In their raw form, frames are stored the same as images, with each pixel having a value that
can be represented using a colour model such as RGB. To improve colour efficiency, frames are
often converted from the RGB colour model to a different one such as YUV. This helps with
compression, as this colour model emphasizes luminance (brightness), which the human eye
is more sensitive to than changes in colour detail.
However, we cannot store frames in the same way as we store photos because, in this format,
they would be too large. They need to be compressed, and there are two main techniques used
for this: spatial (intraframe) and temporal (interframe).
A1 Computer fundamentals
Compression techniques
Spatial compression is particularly effective and commonly used for video that has significant
detail variation in each frame. It reduces file size by eliminating redundant information
within each frame, such as colour depth or detail levels. This approach is important for videos
with a lot of detail that may change significantly between frames, such as animations, nature
documentaries and live news broadcasts.
Temporal compression is particularly effective and commonly used for video that has
consistent motion across frames. It reduces file size by eliminating redundant information
between consecutive frames, capturing only the changes or movements from one frame to the
next. As a predictive compression technique, it predicts frame content based on the preceding
and sometimes following frames, only storing the differences. This approach is important for
videos with a lot of detail that may change significantly between frames, such as animations,
nature documentaries and live news broadcasts.
1 What is the role of frames in a video, and how do they create the illusion of motion?
2 Explain the difference between spatial compression and temporal compression in
video storage.
3 Describe how converting video frames from the RGB colour model to the YUV colour
model can improve compression efficiency.
4 Calculate the total storage needed for a 10-minute video with a frame rate of 30 frames
per second, using 24-bit colour depth and a resolution of 1920x1080 pixels. Assume
no compression.
Signed binary
This includes methods for representing both positive and negative integers.
Two’s complement:
Two's complement is a method for representing signed integers in binary, where the most
significant bit (MSB) indicates the sign (0 for positive, 1 for negative). To convert a positive
binary number to its negative counterpart in two’s complement, you first invert all the bits
(change 0s to 1s and 1s to 0s) and then add 1 to the least significant bit (LSB).
For example:
00000101 = +5
Invert the bits
11111010
Add 1
11111011 =5
Binary-coded decimal
Binary-coded decimal (BCD) is a method of representing decimal numbers where each digit
of the decimal number is encoded separately into its own binary form. Unlike pure binary
representation, which converts the entire decimal number into a single binary sequence, BCD
assigns a 4-bit binary code to each decimal digit (0-9).
For example:
0100 0101 = 45
as 0100 represents 4, and 0101 represents 5
This system is useful where exact decimal representation is crucial, such as financial
applications or digital clocks, as it avoids the rounding errors that can occur in other systems.
However, due to using four bits per digit, more bits are required to store numbers, making it
less space efficient than pure binary representations. Calculations using BCD are also more
complex as they require additional steps to handle carry and overflow, so they are not good
choices for general-purpose computing.
A1 Computer fundamentals
Gray code (reflected binary code)
Gray code is a binary system where two successive values are only allowed to differ by one bit.
That makes this system particularly useful in situations where data integrity during transitions
is important. An example system is a robotic arm where we want to monitor its position. As
the arm rotates, the rotary encoder generates a sequence of binary outputs corresponding
to the arm’s angle. If the encoder used standard binary code, small mechanical vibrations or
inaccuracies could cause multiple bits to change simultaneously, leading to incorrect readings.
However, by using Gray code, the risk of these transition errors is minimized.
B Comparison of Gray code to standard binary for the numbers 0-7
0 000 000
1 001 001
2 010 on
3 on 010
4 100 110
5 101 m
6 110 101
7 m 100
0101
0001
In an 8-bit system, Excess-127 is often used, which adds 127 to encode an 8-bit number and
subtracts 127 to decode it. If you consider trying to order a set of signed binary numbers, this
can be difficult as the negative numbers are larger binary numbers than the positive.
Tor example, take 127 and —127 (using sign-magnitude):
Pre-encoded numbers:
01111111 =127
10000001 =127
When we encode these numbers with Excess-127, the positive numbers now appear larger than
the negative numbers, making them easier to put in order:
Encoded numbers (Excess-127):
127 + 127 = 254
11111110
—127 + 127 =0
00000000
Fixed-point representation
Fixed-point representation is a method used to store real numbers (numbers with fractional
parts) in binary by fixing the position of the binary point. In a fixed-point system, the binary
point is placed at a predetermined position, either between certain bits or at a specific location
in the binary sequence. This allows for a straightforward representation of fractional numbers,
though with some trade-offs in terms of precision and range.
For example, if we want to represent 5.25 in an 8-bit system where four bits represent the
integer and four bits represent the fractional part:
Integer part (four bits): 0101 = 5
Combined: 0101.0100
Note: Binary fractions are used for the fractional part, where the first bit to the right represents
! the second bit represents ! the third } and the fourth &. So, in the example above, we have 04
,14,03and
04
The number of bits assigned in this system limits the range and precision. In this example,
with a 4-bit signed integer, we only have the range of -8 to 7.9375, with the smallest
representable value being 0.0625 (35). This means this system is unable o handle very large
or very small numbers effectively. However, it is a simpler and faster system compared to
floating-point arithmetic (see below), and does not require any complex operations to adjust
the position of the binary point.
Floating-point representation
Floating-point representation is a method used to represent real numbers that can have a
very large range or fractional parts. It does this by storing numbers in a format that includes a
sign, an exponent and a mantissa (or significand). This formar allows computers to efficiently
handle very large numbers, very small numbers and numbers with fractional parts, all with a
reasonable degree of precision.
Using the IEEE 754 standard for single-precision floating-point numbers (which uses 32 bits):
1 Sign bit (one bit):
The sign bit determines whether the number is positive or negative.
2 Exponent (eight bits):
This is used to scale the number by a power of two and is stored using the Excess-127
system in its “biased” form; in other words, 127 is added to the actual exponent value.
3 Mantissa (23 bits):
This represents the significant digits of the number. The mantissa does not store leading
ones (in normalized form).
A1 Computer fundamentals
For example, this is how we could represent the decimal number -5.75:
Convert the number to binary:
101.11
Normalize this number to the form of Lxxxxx x 2™
1.0111 x 22
Determine the components:
Sign bit: 1 (as it is a negative number)
Exponent: 2 + 127 (Excess-127) = 129 = 10000001
Mantissa: 01110000000000000000000 (ignoring the leading 1)
So, the IEEE 754 single-precision binary representation of —3.75 is:
1 (sign) 10000001 (exponent) 01110000000000000000000 (mantissa)
This system allows for the representation of both very large and very small numbers, which is
essential in scientific computing, engineering and graphics, and is more precise than fixed-
point representation.
However, it is still not precise enough to represent all decimal numbers, and this can lead
to rounding errors. The complexity of the system also makes it slower than others, often
requiring special handling in hardware.
Transistor
Electrode Electrode
source
T Electrode T Electrode
Control wire / drain Control wire
M A Buffer gate that shows the inner workings of the gate - B When electricity flows down the control wire, the transistor
when the control wire is off, no electricity can flow between allows for the flow of electricity between electrodes
the electrodes
Above is a simple Buffer gate, where we can consider the control wire as the input and the
electrode drain as the ourput. If the input is on, the output is on; and if the input is off, the
output is off. We can show this using a truth table:
Buffer gate truth table
Input A Output X
1 1
0 0
@ A1 Computer fundamentals
AND gate
The diagram on the left shows an AND gate implemented
- -. / =, Va Output
N N/ using transistors. The gate has two inputs and one output.
If only one of the inputs is on, one of the transistors
without an input would stop the current passing through.
It is only when both inputs are high (1) that the transistors
Input Input allow current to pass through, resulting in a high output (1).
Current - Qutput A—
X
B—
W AND gate
M Input and output rules: The AND gate outputs 1 only if both
inputs are 1
Transistor A Transistor B
AND gate truth table
Current > Output
Input A Input B Output X
0 0 0
0 1 0
1 0 0
Transistor A Transistor B
1 1 1
M Transistor-level schematic of an AND gate
OR gate
The diagram on the left shows an OR gate implemented
using transistors. The gate has two inputs — A and B —
Current Output
and one output. When either input A or B is high (1), the
corresponding transistor turns on, allowing current to
flow through the circuit and resulting in a high ourpur (1).
Transistor A © Transistor B
When both inputs are low (0), neither transistor conducts
and the ourput remains low (0).
—_— [ On |
Current @ s Output
B OR gate
Transistor A | Transistor B
El Off | M Input and output rules: The OR gate outputs 1 if at least one
input is 1
M Transistor-level schematic of an OR gate
OR gate truth table
Input A Input B Output X
0 0 0
0 1 1
1 0 1
1 1 1
T Ground
Input A X
B NOT gate
When the input is high (1), the transistor turns on, allowing
— current to flow from the source to the drain, effectively
Outout grounding the output and resulting in a low voltage at the
utpu
* output (0). When the input is low (0), the transistor turns
off, preventing current from flowing to the ground. In this
state, the output then outputs a high voltage (1).
¥ Current M Input and output rules: The NOT gate outputs the opposite
value of the input
1 > "
B How a NAND gate is constructed: an AND gate followed by a NOT gate B NAND gate
M Input and output rules: The NAND gate outputs 1 unless both inputs are 1
0 0 1
0 1 1
1 0 1
1 1 0
A1 Computer fundamentals
NOR gate (NOT OR)
An NOR gate gives the opposite output to an OR gate as it is constructed using an OR gate
followed by a NOT gate. This means that it is only when both inputs are low (0) that the output
is high (1). In all other cases, the output is low (0).
. A
X
— B
M How a NOR gate is constructed: an OR gate followed by a NOT gate B A NOR gate
M Input and output rules: The NOR gate outputs 1 only if both inputs are 0
0 0 1
0 1
o
1 0
o
1 1
31—
By
. )
M How an XOR gate is constructed M An XOR gate
M Input and output rules: The XOR gate outputs 1 if the inputs are different
0 0 0
0 1 1
1 ] 1
1 1 0
M How an XNOR gate is constructed: an XOR gate followed by a NOT gate M An XNOR gate
M Input and output rules: The XNOR gate outputs 1 if the inputs are the same
0 0 1
0 1 0
1 0 0
1 1 1
B L =
e 1 i
14 II |I
| I
I
I — I
TN I
I R} I
I L S I
|
1
|
|
I
’ X
I [
| I
| I
N | I
| I
f\Q) I I
= I [
e 1I iI
| I
1
T
i
L
part 1 part 2 part3
When creating a truth table, first enter the three inputs and their possible input states; in this
case, A, Band C. As there are three inputs, you can calculate the number of rows you will need
by 2", where n represents the number of inputs. In this example:
2°=8
Populate the furthest right column, alternating between 0 and 1.
Populate the middle column by alternating, every two rows, between 0 and 1.
Populate the left-hand column by alternating, every four rows, berween 0 and 1.
A1 Computer fundamentals
Following this pattern will give you every possible input state.
A B C
0 0 0
0 0 1
0 1 0
0 1 1
1 0 0
1 0 1
1 1 0
Once this is complete, we then add the intermediate values to make it easier to remember the
state at each stage of the circuit. In this example, we have three intermediate values: P, Q and
R. Finally, we add the output column, X.
A B C P Q R
0 0 0
0 0 1
0 1 0
0 1 1
1 0 0
1 0 1
1 1 0
Now, starting with the intermediate values, work through the logic circuit.
A B [« P Q R X
(AANDB) (BNORC) | (PORQ) | (CXORR)
0 0 0 0 1 1 1
0 0 1 0 0 0 1
0 1 0 0 0 0 0
0 1 1 0 0 0 1
1 0 0 0 1 1 1
1 0 1 0 0 0 1
1 1 0 1 0 1 1
1 1 1 1 0 1 0
{>c X
A1 Computer fundamentals
———
B Truth tables to determine outputs from inputs for a
problem description
Problem description: A baby alarm that goes off when the alarm is switched on and the baby is
crying or the room is too cold.
With a problem description, we first need to identify the inputs. Here we have three: alarm
switch, baby crying and room temperature, which we can represent as A, B and C and set up
our truth table.
We know the alarm goes off if the device is switched on AND the baby is crying OR the room
is too cold. From here, we can identity the logic gates in the description. We can determine
from this that the device must be switched on before the alarm can go off, so if the switch is
off, all outputs would be 0. If the device is switched on, at least one of the other two inputs
must be on for the alarm to trigger. We have one intermediate value (baby crying OR room is
cold), represented with P.
A B C P X
(switch) (crying) (cold) (BorQ) (A and P)
0 0 0 0 0
[¢] 0 1 1 0
0 1 4] 1 0
] 1 1 1 0
1 0 0 0 0
1 0 1 1 1
1 1 4] 1 1
1 1 1 1 1
B Logical expressions
We can represent logic circuits using Boolean algebra. If we use the baby alarm scenario again,
we can represent this as:
X=A-(B+(C)
In Boolean algebra, parentheses are often used to indicate which operations should be
performed first. However, there is a standard order of operations, similar to PEMDAS
(or BODMAS) in mathematics. If no parentheses are present, follow this sequence:
m NOT
B AND (including NAND)
This ensures that operations are executed in the correct order for accurate results.
Using the Boolean algebra from the gates in Section A1.2.3, write the Boolean algebra for the
three logic circuits created in the previous problem descriptions:
1 Traffic light control system
2 Water irrigation system
3 Nuclear missile launcher
Two inputs
This two-input K-map is used for expressions with two variables. In this map, variable A is
placed along the side and variable B across the top. llowever, the order of the variables doesn’t
matter — B could be along the side and A across the top. Both possible states (0 and 1) for each
variable are shown in the map, representing all combinations of their values.
A1 Computer fundamentals
Expression: A + B
K
ANB
—
| Qo
-
‘We split the expression at the OR operator and focus first on the term involving A. We
populate the K-map where A is 1, which, in this case, corresponds to the entire bottom row. At
this stage, we ignore B and only fill in the cells where A is 1.
B
-
=
=|l
=
L
Expression: A-B+A - B
This is a more complicated expression, but still has only two inputs. Using this expression, the
circuit would look like this:
T
We again split the expression at the OR symbol, focusing initially on A - B. In this case, we
insert a 1 into only one cell, where both A and B are 1.
A\B
0 1
Next, we focus on the second part of the expression, A - B. In this case, we insert a 1 into the
cell where Ais 1 and Bis 0.
ANB
The K-map is now complete and shows that the value of B has no impact on the outcome,
allowing us to simplify the expression to just A. If we create the circuit using this simplified
expression, we can see that the circuit is significantly more efficient, while still performing the
same function.
A - -
Three inputs
Expression: A-B-C+A-B-C+A-B.C
With three inputs, we use a similar K-map but, this time, we place two of the inputs across the
top. The digits across the top may seem out of order compared to standard binary counting
(00, 01, 10, 11). Instead, they follow the Gray code convention (see Section A1.2.2 for more
information), where only one digit changes at a time. It is important to set the map up this way
to ensure correct grouping and simplification.
AB
C\AB
00 o n 10
We now follow similar steps as with the two-input K-map. We separate the expression by
the OR operator and focus on the first term: A - B - C. In this step, we populate the K-map by
inserting a 1 into the cells where Ais 0,Bis 1 and Cis 1.
A1 Computer fundamentals
AB AB AB AB
C\AB
00 01 1" 10
0
1 1
1 1 1
! L1 L] jnedl)
C\AB
00 01 1 10
The second group, like the first, is located along the bottom row, meaning that C stays as 1
because it does not change across the group. In this case, A remains 1 in both cells, while
B changes from 0 to 1. Since B changes, we discard B from this part of the expression. As a
result, we keep A and C, giving us the second part of our expression:
A-C
We then combine these expressions with an OR operator, giving us the final expression:
B-C+A-C
(.-Common mistake
When setting up your K-map for three inputs, make sure to use Gray code for the headings, not
standard binary. Gray code ensures that only one bit changes between adjacent cells, which helps
when grouping 1s and simplifies the expression more effectively.
1 1] 1 1
However, K-maps are considered three-dimensional, and groups can be formed from left
to right and top to bottom (although only left to right is possible with three inputs). In this
example, it is possible to build a larger group by combining the two groups on the edges,
forming a square group of four 1s.
AB AB AB AB
C\AB
00 01 1 10
k
1 1 1
A1 Computer fundamentals
Using these groups, we can form the simplified expression:
A-C+B
I
B+A-B
NS
Draw the truth table for the above expression.
Draw the Karnaugh map for the expression and
write the simplified expression.
‘B-C+A-B-C+A-B-C
Draw the truth table for the above expression.
& w
Draw the Karnaugh map for the expression and
write the simplified expression.
‘B-C+A-B-C+A-B-C
UI
Draw the truth table for the above expression.
Draw the Karnaugh map for the expression and
write the simplified expression.
: ——.
VYT Y YT
Connect both the outputs to an AND gate.
—
Now work outside the parentheses and introduce the OR gate to link them together.
>
Create the digital circuits from the following Boolean expressions.
1 Y=(A.B@DA
Y=(A+B)-A.B
wN
Y=4A.TB+0
Y=(A®B)
- B®CO
B
Y=(A.B).C+{A+B)
i
A1 Computer fundamentals