Salta al contenuto
Note per Studenti Representation of Information Report

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: N⊂Z⊂Q⊂R\mathbb{N} \subset \mathbb{Z} \subset \mathbb{Q} \subset \mathbb{R}.

set meaning
N={0,+1,+2,… }\mathbb{N}=\{0,+1,+2,\dots\} natural numbers
Z={…,−2,−1,0,+1,+2,… }\mathbb{Z}=\{\dots,-2,-1,0,+1,+2,\dots\} integers
Q={mn∣m∈Z, n∈Z, n≠0}\mathbb{Q}=\{\frac{m}{n} \mid m\in\mathbb{Z},\ n\in\mathbb{Z},\ n\neq 0\} rational numbers
R\mathbb{R} (for example 2,3,π,e,ln⁡2\sqrt{2},\sqrt{3},\pi,e,\ln 2) real numbers

The numbers we write every day use base-10 (decimal) positional notation:

  • base 10: ten digits (symbols) S={0,1,…,9}S=\{0,1,\dots,9\};
  • 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.

435=4⋅102+3⋅101+5⋅100435 = 4\cdot 10^2 + 3\cdot 10^1 + 5\cdot 10^0

Generalization to a base bb (with b∈Nb\in\mathbb{N}, b>1b>1). A sequence of nn digits an−1an−2…a0a_{n-1}a_{n-2}\dots a_0 represents

q=∑k=0n−1ak bk,ak∈S={s0,s1,…,sb−1}q=\sum_{k=0}^{n-1} a_k\, b^k,\qquad a_k\in S=\{s_0,s_1,\dots,s_{b-1}\}

In base bb exactly bb symbols are needed, and they stand for the integers 0,1,…,b−10,1,\dots,b-1. The same idea gives the decimal separator for rational numbers: the fractional part uses negative powers of the base, for example 4.34=4⋅100+3⋅10−1+4⋅10−24.34 = 4\cdot10^0+3\cdot10^{-1}+4\cdot10^{-2}. 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 S={0,1}S=\{0,1\} (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.

11012=(1⋅23+1⋅22+0⋅21+1⋅20)10=13101101_2=(1\cdot2^3+1\cdot2^2+0\cdot2^1+1\cdot2^0)_{10}=13_{10}

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

10010=11001002100_{10}=1100100_2. The algorithm works because at every step ni=2qi+rin_i=2q_i+r_i with ri∈{0,1}r_i\in\{0,1\}; substituting the quotients recursively gives a sum of remainders times powers of 2.

Any base b>1b>1: same algorithm, dividing by bb. Example, 100 to octal (base 8):

100 / 8 = 12 remainder 4
 12 / 8 =  1 remainder 4
  1 / 8 =  0 remainder 1

10010=1448100_{10}=144_8. Check: 1⋅82+4⋅81+4⋅80=64+32+4=1001\cdot8^2+4\cdot8^1+4\cdot8^0=64+32+4=100.

Theorem of division with remainder

At each step we need a pair q,rq,r with k=q⋅base+rk=q\cdot\text{base}+r. The theorem says it always exists and is unique:

Given x∈Zx\in\mathbb{Z} and β∈N\beta\in\mathbb{N}, β>0\beta>0, there exists a unique pair q∈Zq\in\mathbb{Z}, r∈Nr\in\mathbb{N} with 0≤r<β0\le r<\beta such that x=q⋅β+rx=q\cdot\beta+r.

  • Existence. The intervals [nβ,(n+1)β[[n\beta,(n+1)\beta[, n∈Zn\in\mathbb{Z}, cover the whole integer axis. So xx lies in one of them, say the qq-th: qβ≤x<(q+1)βq\beta\le x<(q+1)\beta. Defining r=x−qβr=x-q\beta guarantees 0≤r<β0\le r<\beta.
  • Uniqueness. Suppose two different pairs (q1,r1)(q_1,r_1), (q2,r2)(q_2,r_2) with x=q1β+r1=q2β+r2x=q_1\beta+r_1=q_2\beta+r_2. Then (q1−q2)β=r2−r1(q_1-q_2)\beta=r_2-r_1. Since 0≤r1,r2<β0\le r_1,r_2<\beta we have −β<r2−r1<β-\beta<r_2-r_1<\beta, hence −1<q1−q2<1-1<q_1-q_2<1. Both are integers, so q1=q2q_1=q_2, and then r1=r2r_1=r_2: contradiction.
  • Uniqueness depends on rr being a natural number in [0,β−1][0,\beta-1].

Finite number of bits

With nn bits there are 2n2^n patterns (arrangements with repetition of two symbols), so exactly 2n2^n unsigned integers, in the range [0,2n−1][0,2^n-1]. With 8 bits: 010=0000 000020_{10}=0000\,0000_2, 110=0000 000121_{10}=0000\,0001_2, ..., 25510=1111 11112=27+26+⋯+20255_{10}=1111\,1111_2=2^7+2^6+\dots+2^0.

bits different numbers
282^8 256
2162^{16} 65 536
2322^{32} 4 294 967 296

3. Signed integers

In computer science Z\mathbb{Z} 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 nn-bit two's complement the sequence an−1an−2…a1a0a_{n-1}a_{n-2}\dots a_1a_0 means

−an−12n−1+an−22n−2+⋯+a121+a020=−an−12n−1+∑i=0n−2ai2i-a_{n-1}2^{n-1}+a_{n-2}2^{n-2}+\dots+a_12^1+a_02^0=-a_{n-1}2^{n-1}+\sum_{i=0}^{n-2}a_i2^i

The most significant bit (the leftmost one) gives a negative contribution. With nn bits the range is from −2n−1-2^{n-1} to +2n−1−1+2^{n-1}-1 (with 8 bits: from −128-128 to +127+127). 8-bit table:

decimal 8-bit two's complement
+127+127 0111 1111
+126+126 0111 1110
+1+1 0000 0001
00 0000 0000
−1-1 1111 1111
−127-127 1000 0001
−128-128 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 (2n2^n 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 n−1n-1 is ignored.

An equivalent definition: for a≥0a\ge0 use the unsigned representation of aa on nn bits; for a<0a<0 use the unsigned representation of a+2na+2^n. Example, −13-13 on 8 bits: −13+256=243=1111 00112-13+256=243=1111\,0011_2.

Sign-magnitude

The most significant bit is a sign bit (0 is +, 1 is -), the other bits are the absolute value:

an−1…a0=(−1)an−1∑i=0n−2ai2ia_{n-1}\dots a_0=(-1)^{a_{n-1}}\sum_{i=0}^{n-2}a_i2^i

Range with nn bits: −(2n−1−1)-(2^{n-1}-1) to 2n−1−12^{n-1}-1 (8 bits: −127-127 to +127+127). Examples on 6 bits: 0011002=+12001100_2=+12, 1011002=−12101100_2=-12. It is very seldom used because:

  • it has two representations of zero (+0=0000 0000+0=0000\,0000 and −0=1000 0000-0=1000\,0000), 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 an−1…a0a_{n-1}\dots a_0
unsigned integer ∑i=0n−1ai2i\sum_{i=0}^{n-1}a_i2^i
two's complement −an−12n−1+∑i=0n−2ai2i-a_{n-1}2^{n-1}+\sum_{i=0}^{n-2}a_i2^i
sign-magnitude (−1)an−1∑i=0n−2ai2i(-1)^{a_{n-1}}\sum_{i=0}^{n-2}a_i2^i

Example with the sequence 1111 1111:

  • 8-bit two's complement: −27+26+⋯+20=−1-2^7+2^6+\dots+2^0=-1;
  • 16-bit two's complement: 0000 0000 1111 11112=+2550000\,0000\,1111\,1111_2=+255 (leading zeros on the left can be omitted);
  • 8-bit sign-magnitude: (−1)7(26+⋯+20)=−127(-1)^7(2^6+\dots+2^0)=-127;
  • unsigned 8 bits: 255255.

Addition and overflow

Column addition rules: 0+0=00+0=0, 0+1=1+0=10+1=1+0=1, 1+1=01+1=0 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  +3

Overflow error: the result cannot be represented with the available bits. With 8 bits the range is [−128,+127][-128,+127], so 127+1=128127+1=128 and −128−1=−129-128-1=-129 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 a+b∉[−2n−1,2n−1−1]a+b\notin[-2^{n-1},2^{n-1}-1]. Further examples with 4 bits (range [−8,7][-8,7]): 6+2=86+2=8 gives 0110+0010=10000110+0010=1000, which is −8-8, not +8+8; (−3)+(−7)=−10(-3)+(-7)=-10 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:

  1. take the one's complement (every 0 becomes 1 and every 1 becomes 0);
  2. 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: −x=xˉ+1(mod2n)-x=\bar{x}+1 \pmod{2^n}, where xˉ\bar{x} is the bitwise complement. The rule is its own inverse (applying it to −7-7 gives +7+7), and it makes subtraction an addition: a−b=a+(−b)a-b=a+(-b), so one adder plus a bank of inverters does both.

Why it works.

  1. A sequence of nn ones represents −1-1 in nn-bit two's complement. Using 1+x+x2+⋯+xn−1=xn−1x−11+x+x^2+\dots+x^{n-1}=\frac{x^n-1}{x-1} for x≠1x\ne1: 11…1=−2n−1+∑i=0n−22i=−2n−1+2n−1−12−1=−2n−1+2n−1−1=−111\dots1=-2^{n-1}+\sum_{i=0}^{n-2}2^i=-2^{n-1}+\frac{2^{n-1}-1}{2-1}=-2^{n-1}+2^{n-1}-1=-1
  2. For any nn-bit integer kk with one's complement kˉ\bar{k}, k+kˉ=−1k+\bar{k}=-1 (each pair of bits sums to 1, giving all ones). Example: k=1011 0111k=1011\,0111, kˉ=0100 1000\bar k=0100\,1000, sum =1111 1111=−1=1111\,1111=-1.
  3. From k+kˉ=−1k+\bar k=-1 we get −k=kˉ+1-k=\bar k+1.

Special case: the most negative integer. With 8 bits, negating −128-128 (1000 00001000\,0000) gives invert 0111 11110111\,1111, add 1 gives 1000 00001000\,0000 again: +128+128 is outside the range (an overflow).

Decimal to two's complement for negative numbers. Example −61-61 on 8 bits: (1) convert the absolute value with the unsigned algorithm and pad with leading zeros to 8 bits, 6110=0011 1101261_{10}=0011\,1101_2; (2) apply the sign change: one's complement 1100 00101100\,0010, plus 0000 00010000\,0001 gives 1100 00111100\,0011. So −6110=1100 00112-61_{10}=1100\,0011_2.

4. Hexadecimal and octal notation

Hexadecimal is base 16 with 16 symbols 0,…,9,A,B,C,D,E,F0,\dots,9,A,B,C,D,E,F where A=10A=10, B=11B=11, C=12C=12, D=13D=13, E=14E=14, F=15F=15. 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 16=2416=2^4) and replace each group with one hex digit. Example: 0111 11112=7F160111\,1111_2=7F_{16}. A 32-bit example: 1111 0001 1010 1110 0010 0111 1000 0101 becomes F 1 A E 2 7 8 5, that is F1AE 278516F1AE\,2785_{16}.
  • Hex to binary: replace each hex digit with its four bits. 3F16=0011 111123F_{16}=0011\,1111_2.
  • Hex to decimal: positional definition. A3F16=10⋅162+3⋅161+15⋅160=2560+48+15=262310A3F_{16}=10\cdot16^2+3\cdot16^1+15\cdot16^0=2560+48+15=2623_{10}.
  • 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

100010=3E8161000_{10}=3E8_{16}. Alternatively 100010=11 1110 10002=0011 1110 10002=3E8161000_{10}=11\,1110\,1000_2=0011\,1110\,1000_2=3E8_{16}.

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 8=238=2^3, bits are grouped three at a time from the right (add leading zeros to complete the group). (31)8=3⋅8+1=2510(31)_8=3\cdot8+1=25_{10}; (100010)2=(42)8(100010)_2=(42)_8; (11100010)2=011 100 010=(342)8(11100010)_2=011\,100\,010=(342)_8. 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: nn bits give 2n2^n values while every rational or real interval contains infinitely many numbers (even [0,1[[0,1[ holds 12,13,14,…\frac12,\frac13,\frac14,\dots). 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:

14.34=1⋅101+4⋅100+3⋅10−1+4⋅10−214.34=1\cdot10^1+4\cdot10^0+3\cdot10^{-1}+4\cdot10^{-2} 11.1012=(1⋅21+1⋅20+1⋅2−1+0⋅2−2+1⋅2−3)10=3.6251011.101_2=(1\cdot2^1+1\cdot2^0+1\cdot2^{-1}+0\cdot2^{-2}+1\cdot2^{-3})_{10}=3.625_{10}

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)

0.3510=0.01011020.35_{10}=0.010110_2, 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: 1024.3=1.0243⋅1031024.3=1.0243\cdot10^3 (single digit as integer part; 0.02430.0243 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: 1101=1.101⋅231101=1.101\cdot2^3, 0.0010=1.0⋅2−30.0010=1.0\cdot2^{-3}. 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:

(−1)S(1+∑i=1pMi−12−i)2E(-1)^S\Big(1+\sum_{i=1}^{p}M_{i-1}2^{-i}\Big)2^E

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 1011.11=1.01111⋅231011.11=1.01111\cdot2^3. 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 Ereal=Estored−127E_\text{real}=E_\text{stored}-127. The exponents from −126-126 to +128+128 are represented (from −1023-1023 to +1024+1024 in double).

Special values.

value sign exponent fraction
zero 0 exponent −127-127 (all zeros): 00000000 all zeros
+∞+\infty (result of a/0.0a/0.0, a>0a>0) 0 full ones (+128) all zeros
−∞-\infty (result of a/0.0a/0.0, a<0a<0) 1 full ones all zeros
NaN, Not a Number (for example 0.0/0.00.0/0.0) 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 +0+0 or −0-0 when exponent and fraction are all zeros. Typical NaN results: 0/00/0, −1\sqrt{-1} in real arithmetic, ∞−∞\infty-\infty.

Subnormal (denormalized) numbers (supplementary note): exponent field all zeros with a non-zero fraction. The value is (−1)sign×0.fraction×2−126(-1)^{\text{sign}}\times0.\text{fraction}\times2^{-126}: 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: 1.000…0⋅2−126≈1.8⋅10−381.000\dots0\cdot2^{-126}\approx1.8\cdot10^{-38};
  • largest absolute value: 1.111…1⋅2+127≈3.4⋅10+381.111\dots1\cdot2^{+127}\approx3.4\cdot10^{+38}.

Distance between successive numbers. Two neighbouring representable numbers differ by the least significant bit of the fraction, so their distance is

δ=2−23⋅2E\delta=2^{-23}\cdot2^{E}

where EE is the exponent value. Example: a=1.0…0⋅25=32a=1.0\dots0\cdot2^5=32; the next number is (1+2−23)⋅25(1+2^{-23})\cdot2^5, so δ=2−23⋅25=2−18\delta=2^{-23}\cdot2^5=2^{-18}. With E=23E=23, δ=1\delta=1 (numbers 8 388 6088\,388\,608 and 8 388 6098\,388\,609); with E=27E=27, δ=16\delta=16 (numbers 134 217 728134\,217\,728 and 134 217 744134\,217\,744). 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 10.5+0.12510.5+0.125:

  • 10.510=1010.12=1.01012⋅2310.5_{10}=1010.1_2=1.0101_2\cdot2^3;
  • 0.12510=0.0012=1.0⋅2−30.125_{10}=0.001_2=1.0\cdot2^{-3};
  • same exponent: 1.0101⋅23+0.000001⋅23=1.010101⋅231.0101\cdot2^3+0.000001\cdot2^3=1.010101\cdot2^3.

If the fraction had fewer than 6 bits, the result would be 10.5+0.125=10.510.5+0.125=10.5, because of the approximation introduced by the representation. Another case (supplementary note): 4.354.35 has no exact binary representation (as 1/31/3 has no finite decimal one), and 4.35×100=434.99999999999999944.35\times100=434.9999999999999994, 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, 216=655362^{16}=65536 characters, virtually all characters of existing human alphabets (the slides say about 64 000 defined). For example, 'A' is 0x0041 and the Arabic letter LAM is 0x0644.
  • ASCII (American Standard Code for Information Interchange): a subset of Unicode still widely used; 7 bits, so 27=1282^7=128 characters. The first 128 Unicode codes coincide with the Basic Latin set, which is ASCII.
  • Extended ASCII (supplementary note): 8 bits (1 byte), 28=2562^8=256 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 0000 0000 0000 000120000\,0000\,0000\,0001_2; the character '1' in 16-bit Unicode is 0x0031 =0000 0000 0011 0001=0000\,0000\,0011\,0001.

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 ×\times 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 28=2562^8=256 colours, with 16 bits 216=65 5362^{16}=65\,536 colours. Storage needs many numbers: a 1280x1024 image with 16-bit colours (2 bytes) needs 1280⋅1024⋅2=2 621 4401280\cdot1024\cdot2=2\,621\,440 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, 2n2^n values in [0,2n−1][0,2^n-1]
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 an−1…a0a_{n-1}\dots a_0 in base bb represents q=∑k=0n−1ak bkq=\sum_{k=0}^{n-1} a_k\, b^k; positions count from right to left starting at 0. Fractional digits use negative powers. Binary uses S={0,1}S=\{0,1\}, because two physical states are easier to tell apart.

Unsigned integers. nn bits give 2n2^n values in [0, 2n−1][0,\,2^n-1] (8 bits: 0 to 255).

  • Binary to decimal: sum of bit times power of 2 (for example 11012=13101101_2 = 13_{10}).
  • Decimal to base bb: divide by bb, keep the remainders, stop when the quotient is 0, read the remainders from last to first. 10010=11001002=1448100_{10} = 1100100_2 = 144_8.

Signed integers (two's complement, the standard). The leftmost bit has weight −2n−1-2^{n-1}. Range [−2n−1, 2n−1−1][-2^{n-1},\, 2^{n-1}-1] (8 bits: −128-128 to +127+127). Zero has one representation; addition is plain binary addition, carries beyond bit n−1n-1 are ignored.

  • Negation: invert all bits and add 1, −x=xˉ+1(mod2n)-x=\bar{x}+1 \pmod{2^n}. Example: +7=0000 0111+7 = 0000\,0111, −7=1111 1001-7 = 1111\,1001.
  • 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 0…9,A…F0\dots9, A\dots F, prefix 0x. Binary to hex: groups of four bits from the right (0111 11112=7F160111\,1111_2 = 7F_{16}). Hex to decimal is positional: A3F16=262310A3F_{16} = 2623_{10}. Also used for MAC addresses.

Octal. Base 8, groups of three bits from the right: (11100010)2=(342)8(11100010)_2 = (342)_8.

Fractional numbers. Only approximate: nn bits give 2n2^n 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. 0.3510=0.01011020.35_{10} = 0.010110_2 (periodic).
  • IEEE 754 single (32 bits): sign 1 bit, exponent 8 bits in excess 127, fraction 23 bits, with the leading 1 implicit. Value: (−1)S(1+∑i=1pMi−12−i)2E(-1)^S\big(1+\sum_{i=1}^{p}M_{i-1}2^{-i}\big)2^E. Double (64 bits): exponent 11 bits in excess 1023, fraction 52 bits.
  • Special values: zero (exponent and fraction all zeros), ±∞\pm\infty (exponent all ones, fraction zero), NaN (exponent all ones, fraction non-zero), subnormals (exponent zero, fraction non-zero, gradual underflow).
  • Spacing between neighbouring numbers: δ=2−23⋅2E\delta = 2^{-23}\cdot 2^{E} in single precision; it grows with the magnitude.
  • Rounding: 10.5+0.125=10.510.5 + 0.125 = 10.5 if the fraction has fewer than 6 bits; 4.35×1004.35 \times 100 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 1280⋅1024⋅2=2 621 4401280\cdot1024\cdot2 = 2\,621\,440 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 −0-0 as meaningful in two's complement; confusing the number 1 with the character '1' (0x0031); assuming fractional decimals are exact in binary.

Teoria collegata