Representation of Information
In questa pagina 9
Every application, game, image, video, sound and text message is ultimately stored as binary data: sequences of two symbols, conventionally called 0 and 1. Humans handle text, numbers, images, sounds and videos; a computer needs a codinga rule that expresses a piece of information in a format suitable for storing and processing it for each of them. This note covers numbers, text, images, video and sound.
1. Natural numbers and positional notation
Number sets: .
| set | meaning |
|---|---|
| natural numbers | |
| integers | |
| rational numbers | |
| (for example ) | real numbers |
The numbers we write every day use base-10 (decimal) positional notation:
- base 10: ten digits (symbols) ;
- positional: the same digit in different positions has a different weight. The weight is the base raised to the position of the digit; positions are counted from right to left starting from 0.
Generalization to a base (with , ). A sequence of digits represents
In base exactly symbols are needed, and they stand for the integers . The same idea gives the decimal separator for rational numbers: the fractional part uses negative powers of the base, for example . In computer science the point (not the comma) is the separator.
2. Binary representation of unsigned integers
In computer science the natural numbers are called unsigned integers. Computers use base 2 with the two symbols (the bitbinary digit, 0 or 1). Binary is preferred because it is much easier to build electronic logic circuits that tell apart two states (on/off, high/low voltage) than ten different voltage levels.
Binary to decimal: multiply each bit by its power of 2 and add.
Decimal to binary (integer part): divide by 2 with integer division, write the remainder, continue with the quotient until the quotient is 0 (do not stop at quotient 1). The binary number is the sequence of remainders read from the last one to the first.
100 / 2 = 50 remainder 0
50 / 2 = 25 remainder 0
25 / 2 = 12 remainder 1
12 / 2 = 6 remainder 0
6 / 2 = 3 remainder 0
3 / 2 = 1 remainder 1
1 / 2 = 0 remainder 1. The algorithm works because at every step with ; substituting the quotients recursively gives a sum of remainders times powers of 2.
Any base : same algorithm, dividing by . Example, 100 to octal (base 8):
100 / 8 = 12 remainder 4
12 / 8 = 1 remainder 4
1 / 8 = 0 remainder 1. Check: .
Theorem of division with remainder
At each step we need a pair with . The theorem says it always exists and is unique:
Given and , , there exists a unique pair , with such that .
- Existence. The intervals , , cover the whole integer axis. So lies in one of them, say the -th: . Defining guarantees .
- Uniqueness. Suppose two different pairs , with . Then . Since we have , hence . Both are integers, so , and then : contradiction.
- Uniqueness depends on being a natural number in .
Finite number of bits
With bits there are patterns (arrangements with repetition of two symbols), so exactly unsigned integers, in the range . With 8 bits: , , ..., .
| bits | different numbers |
|---|---|
| 256 | |
| 65 536 | |
| 4 294 967 296 |
3. Signed integers
In computer science is the set of signed integers. A sequence of bits can be read in different formats, so to convert it to decimal you must know the format.
Two's complement (the standard)
In -bit two's complement the sequence means
The most significant bit (the leftmost one) gives a negative contribution. With bits the range is from to (with 8 bits: from to ). 8-bit table:
| decimal | 8-bit two's complement |
|---|---|
| 0111 1111 | |
| 0111 1110 | |
| 0000 0001 | |
| 0000 0000 | |
| 1111 1111 | |
| 1000 0001 | |
| 1000 0000 |
Properties:
- the leading bit is 0 for non-negative numbers and 1 for negative numbers;
- zero has a unique representation, and no configuration is wasted ( different numbers);
- the remaining bits are not the absolute value, except for positive numbers;
- addition uses the normal binary addition of the representations, and a carry beyond bit is ignored.
An equivalent definition: for use the unsigned representation of on bits; for use the unsigned representation of . Example, on 8 bits: .
Sign-magnitude
The most significant bit is a sign bit (0 is +, 1 is -), the other bits are the absolute value:
Range with bits: to (8 bits: to ). Examples on 6 bits: , . It is very seldom used because:
- it has two representations of zero ( and ), so one configuration is wasted;
- addition is complicated: signs must be compared and, if different, magnitudes too (if the signs are equal the magnitudes add; otherwise the smaller magnitude is subtracted from the larger and the result takes the sign of the larger).
The same bits, different formats
| format | value of |
|---|---|
| unsigned integer | |
| two's complement | |
| sign-magnitude |
Example with the sequence 1111 1111:
- 8-bit two's complement: ;
- 16-bit two's complement: (leading zeros on the left can be omitted);
- 8-bit sign-magnitude: ;
- unsigned 8 bits: .
Addition and overflow
Column addition rules: , , with a carry of 1. The carry out of the leftmost position can be ignored as long as the result is representable with the available bits.
0000 0101 +5 0000 0101 +5
0000 0010 +2 1111 1110 -2
--------- ---------
0000 0111 +7 1|0000 0011 +3Overflow error: the result cannot be represented with the available bits. With 8 bits the range is , so and cannot be represented:
0111 1111 +127 1000 0000 -128
0000 0001 +1 1111 1111 -1
--------- ---------
1000 0000 -128 ! 1|0111 1111 +127 !How to detect it: look at the carry into/out of the two most significant bits.
| carries | result |
|---|---|
| no carry in the two most significant bits, or carry in both | no overflow |
| carry in only one of the two | overflow |
(The most significant digit is the leftmost one, the least significant is the rightmost; in 102, 1 and 2 are the most and least significant digits.) Equivalent criterion: overflow when . Further examples with 4 bits (range ): gives , which is , not ; is below the minimum, so overflow again.
Sign change algorithm
All computers use two's complement because the algebraic sum is simple to implement. To change the sign of a number:
- take the one's complement (every 0 becomes 1 and every 1 becomes 0);
- add 1.
number to change sign 00000111 (+7) 11111001 (-7)
one's complement 11111000 00000110
add 1 00000001 00000001
number with sign changed 11111001 (-7) 00000111 (+7)In formula: , where is the bitwise complement. The rule is its own inverse (applying it to gives ), and it makes subtraction an addition: , so one adder plus a bank of inverters does both.
Why it works.
- A sequence of ones represents in -bit two's complement. Using for :
- For any -bit integer with one's complement , (each pair of bits sums to 1, giving all ones). Example: , , sum .
- From we get .
Special case: the most negative integer. With 8 bits, negating () gives invert , add 1 gives again: is outside the range (an overflow).
Decimal to two's complement for negative numbers. Example on 8 bits: (1) convert the absolute value with the unsigned algorithm and pad with leading zeros to 8 bits, ; (2) apply the sign change: one's complement , plus gives . So .
4. Hexadecimal and octal notation
Hexadecimal is base 16 with 16 symbols where , , , , , . Humans use it to write binary unsigned integers or bit sequences compactly. In programming languages it is written with the prefix 0x (for example 0x7F).
- Binary to hex: group bits in groups of four from right to left (since ) and replace each group with one hex digit. Example: . A 32-bit example:
1111 0001 1010 1110 0010 0111 1000 0101becomesF 1 A E 2 7 8 5, that is . - Hex to binary: replace each hex digit with its four bits. .
- Hex to decimal: positional definition. .
- Decimal to hex: divide by 16, or go through binary.
1000 / 16 = 62 remainder 8
62 / 16 = 3 remainder E (14)
3 / 16 = 0 remainder 3. Alternatively .
Hex is used for memory addresses and contents (memory dumps) and for MAC addresses: a 12-digit hexadecimal number that uniquely identifies a network interface card, for example 675d:b3d8:82cb (":" is a separator).
Octal is base 8; since , bits are grouped three at a time from the right (add leading zeros to complete the group). ; ; . For the reverse, replace each octal digit with three bits and drop non-significant leading zeros.
5. Fractional numbers
Rational and real numbers are called fractional numbers in computer science: an integer part and a fractional part (3.1415927). They can only be represented approximately: bits give values while every rational or real interval contains infinitely many numbers (even holds ). Two formats exist: fixed point and floating point.
Fixed point
The number of digits for the integer and fractional parts is decided in advance (for example max 4 integer digits and 2 fractional digits: 3.14, 1234.56). The integer part uses non-negative powers of the base, the fractional part negative powers:
Decimal to binary: convert the integer part and the fractional part separately; the position of the dot does not change. The fractional part is converted by repeated multiplication by 2: multiply, the integer part of the product is the next bit, keep only the fractional part and multiply again, until the result is 0 or a value already obtained appears again. The binary number is the sequence of the integer parts of the products, starting from the first.
0.35 * 2 = 0.7 -> bit 0
0.7 * 2 = 1.4 -> bit 1
0.4 * 2 = 0.8 -> bit 0
0.8 * 2 = 1.6 -> bit 1
0.6 * 2 = 1.2 -> bit 1
0.2 * 2 = 0.4 -> bit 0 (0.4 already obtained: it repeats), and the periodic part is 0110 (from the value 0.4 onwards the procedure repeats). If a value repeats the number is periodic in base 2, even if it is not periodic in base 10: a finite decimal can become infinite in binary. Fixed-point formats are used only on processors that do not support floating-point arithmetic or when computation speed is extremely important.
Floating point
Scientific notation with a fraction (mantissa) and an exponent: (single digit as integer part; is the fraction, 3 the exponent). In binary the fraction and exponent are in base 2, because multiplying and dividing by 2 only moves the dot: , . In binary the integer part is always 1. One convention prevailed among the old formats: IEEE 754.
6. IEEE 754 floating-point standard
The original standard (1985) defines two formats, single (32-bit) and double (64-bit) precision. Value:
| field | single precision | double precision |
|---|---|---|
| S, sign bit (most significant bit: 0 positive, 1 negative) | 1 bit | 1 bit |
| E, exponent | 8 bits | 11 bits |
| M, fraction (least significant bits) | 23 bits | 52 bits |
| total | 32 bits | 64 bits |
Normalization. The binary number is written so that the most significant bit is immediately to the left of the dot, for example . That bit is always 1, so it is not stored. The fraction stored (single precision) is 01111000000000000000000. This gains one bit of precision.
Exponent in excess (bias). The exponent is stored in excess 127 on 8 bits (excess 1023 in double precision): it is incremented by 127 before being converted to binary as an unsigned integer (not two's complement), so . The exponents from to are represented (from to in double).
Special values.
| value | sign | exponent | fraction |
|---|---|---|---|
| zero | 0 | exponent (all zeros): 00000000 |
all zeros |
| (result of , ) | 0 | full ones (+128) | all zeros |
| (result of , ) | 1 | full ones | all zeros |
| NaN, Not a Number (for example ) | 0 or 1 | full ones | anything except all zeros |
The exponent +128 (all ones) is used only for special cases; NaN is a special symbol for error conditions, and its fraction must be non-zero to distinguish it from infinity. The sign selects or when exponent and fraction are all zeros. Typical NaN results: , in real arithmetic, .
Subnormal (denormalized) numbers (supplementary note): exponent field all zeros with a non-zero fraction. The value is : the implicit leading part is 0 instead of 1. They represent numbers closer to zero than the smallest normalized one and implement gradual underflow (the values decrease gradually towards zero instead of jumping to zero).
Range (single precision).
- smallest absolute value: ;
- largest absolute value: .
Distance between successive numbers. Two neighbouring representable numbers differ by the least significant bit of the fraction, so their distance is
where is the exponent value. Example: ; the next number is , so . With , (numbers and ); with , (numbers and ). The distance grows as the absolute value grows: the density of representable numbers decreases. This must be taken into account when adding real numbers.
Rounding effects
To add two floating-point numbers they must be brought to the same exponent. Example :
- ;
- ;
- same exponent: .
If the fraction had fewer than 6 bits, the result would be , because of the approximation introduced by the representation. Another case (supplementary note): has no exact binary representation (as has no finite decimal one), and , not exactly 435: the initial rounding error is amplified by the multiplication. The problem is the representation, not the language.
7. Coding of text
Text contains characters, each associated with an unsigned integer. The table that associates characters to numbers is called a codethe table that associates each character with a number; standard codes let computers of different types exchange text. Humans recognize a character by its shape (font), the computer identifies it by a binary integer: the character C is code 0x0043 whatever the font.
- Unicode: 2 bytes (16 bits) per character, characters, virtually all characters of existing human alphabets (the slides say about 64 000 defined). For example, 'A' is
0x0041and the Arabic letter LAM is0x0644. - ASCII (American Standard Code for Information Interchange): a subset of Unicode still widely used; 7 bits, so characters. The first 128 Unicode codes coincide with the Basic Latin set, which is ASCII.
- Extended ASCII (supplementary note): 8 bits (1 byte), characters, adds accented vowels and special letters of Western alphabets; sequences whose first bit is 0 coincide with ASCII, which guarantees compatibility.
- Today Unicode is a more general standard whose abstract characters (code points) have several encodings (UTF-8, UTF-16, UTF-32); for the course it is enough to know that ASCII is part of Unicode and characters are numbers.
ASCII layout.
| codes | content |
|---|---|
| 0 to 31 | control characters; of interest: 9 (0x0009, HT, horizontal tab, '\t'), 10 (0x000A, LF, line feed, '\n'), 13 (0x000D, CR, carriage return, '\r') |
| 32 to 127 | printable characters |
32 (0x0020) |
space ' ' |
| 48 to 57 | decimal digits '0'...'9' |
| 65 to 90 and 97 to 122 | letters A-Z and a-z (upper and lower case) |
| 33-47, 58-64, 91-96, 123-127 | punctuation and symbols |
In Python and most programming languages, tokens (keywords, separators, operators, literals) are defined using only Basic Latin (ASCII) characters, and the course uses only ASCII characters for identifiers too, so Unicode can be ignored in practice (see Python - BasicsPython 3 is a high-level, general-purpose, interpreted language. A program is a sequence of statements run by the interpreter, either interactively at the prompt or from a file with the edit/run loop. Variables are names bound to values by assignment; the basic types are int, float, str and bool, with explicit conversions (int, float, str, bool) and input always returning a string. Arithmetic uses the operators plus, minus, star, slash, double slash, percent and double star with precedence rules, relational operators produce booleans, and and, or, not combine them (precedence not, and, or; De Morgan's laws).Python - Basics →).
Do not confuse numbers and characters. The integer 1 in 16-bit two's complement is ; the character '1' in 16-bit Unicode is 0x0031 .
8. Images, video and sound
Images. An image is discretized into pixels (picture elements), each a single point on the screen. Resolution is the level of detail, that is the count of pixels (pixels per row pixels per column); typical screen resolutions: 640x480, 800x600, 1024x864, 1152x864, 1280x1024. Each pixel is associated with a colour, and each colour with an integer: with 8 bits colours, with 16 bits colours. Storage needs many numbers: a 1280x1024 image with 16-bit colours (2 bytes) needs bytes (about 2.62 Mbytes). For this reason images are stored in formats that use compression (fewer bytes):
| format | compression |
|---|---|
| GIF | reduces bytes without loss of information (lossless) |
| JPEG | loses some information (lossy), e.g. smartphone photos; the quality is still perfectly acceptable to the human eye |
Video. A video is a sequence of images (frames), stored with the MPEG format, an extension of JPEG: only the differences between the current frame and the previous one are stored (YouTube and Netflix streaming).
Sound. Sound is captured, usually by a microphone, which converts it into an analogue signal (voltage); an analogue-to-digital converter then samples the wave at regular time intervals, and each sample is recorded as the nearest integer number and then converted to binary. Plotting the samples back gives a different wave, because sampling does not capture what the wave does between two samples: quality is lost. To get closer to the original, take more samples closer together. The frequency at which samples are taken is the sample rate, measured in Hz (1 Hz is one sample per second); most CD-quality audio is sampled at 44.1 or 48 kHz. The human ear hears from 20 Hz to 20 kHz. To turn digital sound back into sound an output device (the speakers) is needed.
9. Summary
| information | representation |
|---|---|
| unsigned naturals | positional binary, values in |
| signed integers | two's complement (standard) or sign-magnitude (rare) |
| approximated reals | fixed point or IEEE 754 float/double |
| characters | unsigned integer codes: ASCII, Unicode |
| images / video / sound | pixel colours / frame differences (MPEG) / samples |
Versione ripasso
Idea. Everything is binary data; each kind of information needs a codinga rule that expresses a piece of information in a format suitable for storing and processing it.
Positional notation. A digit string in base represents ; positions count from right to left starting at 0. Fractional digits use negative powers. Binary uses , because two physical states are easier to tell apart.
Unsigned integers. bits give values in (8 bits: 0 to 255).
- Binary to decimal: sum of bit times power of 2 (for example ).
- Decimal to base : divide by , keep the remainders, stop when the quotient is 0, read the remainders from last to first. .
Signed integers (two's complement, the standard). The leftmost bit has weight . Range (8 bits: to ). Zero has one representation; addition is plain binary addition, carries beyond bit are ignored.
- Negation: invert all bits and add 1, . Example: , .
- Overflow: detect it from the carries into and out of the two most significant bits. Carry in only one of them means overflow.
- Sign-magnitude (rare): sign bit plus absolute value; two representations of zero and complicated addition.
Hexadecimal. Base 16, digits , prefix 0x. Binary to hex: groups of four bits from the right (). Hex to decimal is positional: . Also used for MAC addresses.
Octal. Base 8, groups of three bits from the right: .
Fractional numbers. Only approximate: bits give values, while every real interval has infinitely many numbers.
- Fixed point: fixed number of integer and fractional digits. Fractional part converted by repeated multiplication by 2, reading the integer parts of the products, until 0 or a value repeats. (periodic).
- IEEE 754 single (32 bits): sign 1 bit, exponent 8 bits in excess 127, fraction 23 bits, with the leading 1 implicit. Value: . Double (64 bits): exponent 11 bits in excess 1023, fraction 52 bits.
- Special values: zero (exponent and fraction all zeros), (exponent all ones, fraction zero), NaN (exponent all ones, fraction non-zero), subnormals (exponent zero, fraction non-zero, gradual underflow).
- Spacing between neighbouring numbers: in single precision; it grows with the magnitude.
- Rounding: if the fraction has fewer than 6 bits; is not exactly 435.
Text. Each character is an unsigned integer in a code table.
- ASCII: 7 bits, 128 characters;
'0'-'9'are 48-57,'A'-'Z'65-90,'a'-'z'97-122, space 32, LF 10, CR 13. - Unicode: 16 bits per character in the course (for example 'A' is
0x0041); ASCII is its first 128 codes.
Images, video, sound.
- Image: pixels, each with a colour code. A 1280x1024 image at 2 bytes per pixel needs bytes. GIF is lossless, JPEG is lossy.
- Video: frames stored as differences from the previous frame (MPEG).
- Sound: sampling at a sample rate in Hz (44.1 or 48 kHz for CD-quality audio); the ear hears 20 Hz to 20 kHz.
Common mistakes: reading bits without knowing the format (the same bits give different values in each format); forgetting the leading bit is the sign in two's complement; treating as meaningful in two's complement; confusing the number 1 with the character '1' (0x0031); assuming fractional decimals are exact in binary.