কম্পিউটার বিজ্ঞান · বই 2 · শ্রেণি 10–12

High School Computer Science

এই বইটি এখনো বাংলা ভাষায় পাওয়া যায় না। সংস্করণ: English।

High School Computer Science · শ্রেণি 10–12

3Integers in the Machine

Noor’s grandfather kept an old step counter clipped to his belt. One summer he walked across a whole region, and each evening he wrote down the number it showed. On the eighth day the number was smaller than on the seventh, although he had walked all day. The counter was not broken. It had six digits on its little screen and, inside, a memory of a fixed number of bits; after the largest number it could hold, it went back to zero, like a car’s odometer.

Every number a processor works on lives in a fixed number of bits. This chapter shows how whole numbers, positive and negative, are written in 88, 1616, 3232 or 6464 bits, what happens when a result does not fit, and how a program can work on the bits of a number one by one.

You already know

A whole number is written in base 22 with the digits 00 and 11, each position worth twice the one on its right; in base 1616 with the digits 00 to 99 and AA to FF; Python’s bin, hex and int(s, 2) convert between bases, and two binary numbers are added column by column with a carry (Book 1, grade 8). A bit is one binary digit and a byte is eight bits (Book 1, grade 5). 210=10242^{10} = 1024, and 2a×2b=2a+b2^{a} \times 2^{b} = 2^{a+b} (mathematics book, grade 8).

3.1 Unsigned integers on nn bits

Base 22 is one base among many. In any base b≥2b \ge 2, a whole number is written with digits from 00 to b−1b - 1, and the digit at position ii (counting from 00 on the right) is worth bib^i times its value. The digits are found from the right by repeated division: the remainder of nn divided by bb is the last digit, and the quotient holds the others.

DIGITS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"


def to_base(n, b):
    """Return the digits of the whole number n >= 0 in base b, 2 <= b <= 36."""
    if n == 0:
        return "0"
    digits = ""
    while n > 0:
        digits = DIGITS[n % b] + digits
        n = n // b
    return digits


for b in (2, 8, 10, 16, 36):
    print(f"2026 in base {b:2}: {to_base(2026, b)}")
print(int("11111101010", 2), int("7EA", 16))
Listing 3.1. Writing a number in any base from 22 to 3636. code/grade-10/03-machine-integers/listings/to_base.py
$ python to_base.py
2026 in base  2: 11111101010
2026 in base  8: 3752
2026 in base 10: 2026
2026 in base 16: 7EA
2026 in base 36: 1KA
2026 2026
Output 3.1. The same number in five bases. int reads a string of digits back in a given base.

A processor does not write numbers with as many digits as needed: its registers and memory cells have a fixed size.

Definition 3.1 (Unsigned integer, nn-bit integer)

An nn-bit integer is a whole number stored in exactly nn bits, bn−1…b1b0b_{n-1} \dots b_1 b_0. Read as an unsigned integer, its value is bn−12n−1+⋯+b12+b0b_{n-1} 2^{n-1} + \dots + b_1 2 + b_0. The usual sizes are 88 bits (one byte), 1616, 3232 and 6464 bits.

Proposition 3.2 (Range of nn bits)

The unsigned integers on nn bits are exactly the whole numbers from 00 to 2n−12^n - 1. A whole number x≥1x \ge 1 needs kk bits, where kk is the number with 2k−1≤x<2k2^{k-1} \le x < 2^k.

Proof. There are 22 choices for each of the nn bits, so 2n2^n patterns, and different patterns have different values (base 22 writing is unique). The smallest value is 00 (all bits 00). The largest has all bits 11: adding 11 to 11…111\dots1 carries through every column and gives 100…0100\dots0, which is 2n2^n; so 11…111\dots1 is 2n−12^n - 1. Hence the 2n2^n values are 0,1,…,2n−10, 1, \dots, 2^n - 1. A number with 2k−1≤x<2k2^{k-1} \le x < 2^k fits in kk bits but not in k−1k - 1, whose largest value is 2k−1−12^{k-1} - 1. ∎

So one byte holds 00 to 255255, 1616 bits hold 00 to 65,53565{,}535, and 3232 bits 00 to 4,294,967,2954{,}294{,}967{,}295.

Python’s method n.bit_length() gives the number of bits that nn needs.

for n in (1, 2, 255, 256, 1000, 65535, 65536):
    print(f"{n:6}  bit_length {n.bit_length():2}")

a = 2**20 - 1  # the largest number on 20 bits
b = 2**13 - 1  # the largest number on 13 bits
print("a + b needs", (a + b).bit_length(), "bits")
print("a * b needs", (a * b).bit_length(), "bits")
Listing 3.2. How many bits a number, a sum and a product need. code/grade-10/03-machine-integers/listings/bits_needed.py
$ python bits_needed.py
     1  bit_length  1
     2  bit_length  2
   255  bit_length  8
   256  bit_length  9
  1000  bit_length 10
 65535  bit_length 16
 65536  bit_length 17
a + b needs 21 bits
a * b needs 33 bits
Output 3.2. Each power of two needs one more bit than the number just below it.

Proposition 3.3 (Bits of a sum and of a product)

If aa fits in pp bits and bb in qq bits, with p≥qp \ge q, then a+ba + b fits in p+1p + 1 bits and a×ba \times b fits in p+qp + q bits.

Proof. a≤2p−1a \le 2^p - 1 and b≤2q−1≤2p−1b \le 2^q - 1 \le 2^p - 1, so a+b≤2p+1−2<2p+1a + b \le 2^{p+1} - 2 < 2^{p+1}. And a×b≤(2p−1)(2q−1)<2p×2q=2p+qa \times b \le (2^p - 1)(2^q - 1) < 2^p \times 2^q = 2^{p+q}. ∎

The run above shows that both bounds can be reached: the largest numbers on 2020 and 1313 bits have a sum of 2121 bits and a product of 3333.

When a result needs more bits than the machine has, the extra bits are simply lost.

Definition 3.4 (Overflow)

An overflow happens when the result of an operation does not fit in the number of bits that hold it. An nn-bit unsigned adder then keeps the nn lowest bits of the true result, that is, the remainder of the true result divided by 2n2^n: the value wraps around.

Python’s % gives that remainder, so a few lines simulate the step counter, here with 1616 bits.

def add_unsigned(a, b, n):
    """Add a and b as an n-bit unsigned adder does: keep the n lowest bits."""
    return (a + b) % 2**n


counter = 0
for step in range(65_540):
    counter = add_unsigned(counter, 1, 16)
    if step >= 65_533:
        print("after", step + 1, "steps the counter shows", counter)

print("8 bits:  250 + 10 =", add_unsigned(250, 10, 8))
print("16 bits: 250 + 10 =", add_unsigned(250, 10, 16))
Listing 3.3. A 16-bit counter, and one addition on 88 and on 1616 bits. code/grade-10/03-machine-integers/listings/wrap.py
$ python wrap.py
after 65534 steps the counter shows 65534
after 65535 steps the counter shows 65535
after 65536 steps the counter shows 0
after 65537 steps the counter shows 1
after 65538 steps the counter shows 2
after 65539 steps the counter shows 3
after 65540 steps the counter shows 4
8 bits:  250 + 10 = 4
16 bits: 250 + 10 = 260
Output 3.3. After 65,53565{,}535 comes 00: a whole walk’s worth of steps has vanished.

The toy machine of the next year (grade 11) has registers of one byte. The same addition, 250+10250 + 10, run on it:

        LOADI R0, 250
        ADDI R0, 10     ; 250 + 10 does not fit in one byte
        HALT
Listing 3.4. Three instructions for the toy machine. code/grade-10/03-machine-integers/listings/toy_wrap.toy
$ python -m toymachine run toy_wrap.toy --dump
R0=4 R1=0 R2=0 R3=0 PC=4 SP=0 Z=0 N=0 C=1
  M[0]=4  M[1]=250  M[2]=24  M[3]=10
Output 3.4. Register R0 holds 44, and the flag C (carry) is 11: the machine kept the lost bit in a flag.

The processor does not stop at an overflow; it records it in its carry flag, and a program that does not look at the flag never knows.

3.2 Signed integers: two’s complement

Negative numbers need a sign, but a memory cell holds only bits. The usual method gives the leftmost bit a negative weight.

Definition 3.5 (Two’s complement)

In two’s complement on nn bits, the pattern bn−1bn−2…b0b_{n-1} b_{n-2} \dots b_0 stands for the signed value

−bn−12n−1+bn−22n−2+⋯+b12+b0.-b_{n-1} 2^{n-1} + b_{n-2} 2^{n-2} + \dots + b_1 2 + b_0 .

The leftmost bit is the sign bit: it is 11 exactly for the negative values.

The weights of the bits of one byte in two’s complement. Only the leftmost weight is negative; the byte of eight 1 bits stands for -1.
The weights of the bits of one byte in two’s complement. Only the leftmost weight is negative; the byte of eight 11 bits stands for −1-1.

The first half of the patterns, those starting with 00, keep their unsigned value; the second half stands for negative numbers. The listing prints the sixteen patterns of 44 bits.

def encode(x, n):
    """Return the n-bit two's complement pattern of x as an unsigned number.

    Precondition: -2**(n-1) <= x < 2**(n-1).
    """
    return x % 2**n


def decode(u, n):
    """Return the signed value of the n-bit pattern u, 0 <= u < 2**n."""
    if u >= 2 ** (n - 1):
        return u - 2**n
    return u


for u in range(16):
    print(f"{u:04b}  unsigned {u:2}  signed {decode(u, 4):3}")
print("encode(-3, 8) =", format(encode(-3, 8), "08b"))
Listing 3.5. Encoding and decoding nn-bit two’s complement. code/grade-10/03-machine-integers/listings/twos.py
$ python twos.py
0000  unsigned  0  signed   0
0001  unsigned  1  signed   1
0010  unsigned  2  signed   2
0011  unsigned  3  signed   3
0100  unsigned  4  signed   4
0101  unsigned  5  signed   5
0110  unsigned  6  signed   6
0111  unsigned  7  signed   7
1000  unsigned  8  signed  -8
1001  unsigned  9  signed  -7
1010  unsigned 10  signed  -6
1011  unsigned 11  signed  -5
1100  unsigned 12  signed  -4
1101  unsigned 13  signed  -3
1110  unsigned 14  signed  -2
1111  unsigned 15  signed  -1
encode(-3, 8) = 11111101
Output 3.5. On 44 bits, from −8-8 to 77. The unsigned and the signed reading differ by 1616 in the second half.

Proposition 3.6 (Range and negation)

The signed integers on nn bits are the whole numbers from −2n−1-2^{n-1} to 2n−1−12^{n-1} - 1. The pattern of xx and its unsigned reading uu satisfy u=xu = x if x≥0x \ge 0 and u=x+2nu = x + 2^n if x<0x < 0. To negate a number, flip every bit and add 11 (keeping nn bits).

Proof. If the sign bit is 00, the value is that of the other n−1n - 1 bits, from 00 to 2n−1−12^{n-1} - 1. If it is 11, the value is −2n−1-2^{n-1} plus a number from 00 to 2n−1−12^{n-1} - 1, so from −2n−1-2^{n-1} to −1-1; and it is the unsigned value, which counts the leftmost bit as +2n−1+2^{n-1}, minus 2×2n−1=2n2 \times 2^{n-1} = 2^n. For the negation, write xˉ\bar x for the pattern with every bit of xx flipped. In each column exactly one of xx and xˉ\bar x has a 11, so the unsigned readings add up to 11…1=2n−111\dots1 = 2^n - 1. Hence xˉ+1=2n−x\bar x + 1 = 2^n - x, which on nn bits is the pattern of −x-x. ∎

Example 3.7 (−5-5 on 8 bits)

55 is 00000101; flipping every bit gives 11111010; adding 11 gives 11111011. Check: −128+64+32+16+8+2+1=−5-128 + 64 + 32 + 16 + 8 + 2 + 1 = -5.

The sixteen patterns of 4 bits on a wheel, with their signed values. Adding 1 moves one step clockwise. The signed overflow is the step from 7 to -8; the unsigned one is the step from 15 (that is, -1) to 0.
The sixteen patterns of 44 bits on a wheel, with their signed values. Adding 11 moves one step clockwise. The signed overflow is the step from 77 to −8-8; the unsigned one is the step from 1515 (that is, −1-1) to 00.

The great advantage of two’s complement is that the addition does not change. Since a negative xx is stored as x+2nx + 2^n, and the adder works modulo 2n2^n, the unsigned adder of the previous section adds signed numbers correctly as long as the true result is in the range. One circuit serves both; grade 11 builds it from gates.

When the true signed result is out of range, the result wraps around the wheel and the sign comes out wrong: 100+50100 + 50 on 88 bits gives the pattern of 150150, which reads as −106-106. This can be spotted without the true result.

Proposition 3.8 (Detecting a signed overflow)

The sum of two signed nn-bit integers overflows exactly when the two operands have the same sign and the result’s sign bit is different.

The proof is Exercise 3.14.

3.3 Working on the bits

Definition 3.9 (Bitwise operation)

A bitwise operation works on each bit position separately. In Python, a & b has a 11 where both a and b have a 11 (and); a | b where at least one has a 11 (or); a ^ b where exactly one has a 11 (exclusive or, xor); and ~a flips every bit (not; for Python’s integers, ~a equals -a - 1).

Definition 3.10 (Shift)

A shift moves every bit of a number by kk positions: a << k to the left, adding kk zeros on the right, and a >> k to the right, dropping the kk rightmost bits. For a whole number a≥0a \ge 0, a << k is a×2ka \times 2^k and a >> k is the quotient a // 2**k.

The most common use of these operations is to pick out, switch on or switch off one bit, using a second number that has 11 bits only at the places of interest.

Definition 3.11 (Mask)

A mask is a number used with a bitwise operation to select some bits of another number: x & m keeps the bits of x where m has a 11 and clears the others; x | m sets them to 11; x ^ m flips them. The mask 1 << i has a single 11, at position ii.

Clearing bit 5 of x (bits are numbered from 0 on the right). The mask has a 0 at position 5 and 1 elsewhere;  copies every bit of x except that one.
Clearing bit 55 of x (bits are numbered from 00 on the right). The mask has a 00 at position 55 and 11 elsewhere; and copies every bit of x except that one.
flags = 0b1010_0110

print(format(flags, "08b"), "bit 2 is", (flags >> 2) & 1)
print(format(flags | (1 << 0), "08b"), "after setting bit 0")
print(format(flags & ~(1 << 5), "08b"), "after clearing bit 5")
print(format(flags ^ 0b1111_1111, "08b"), "after flipping every bit")

colour = 0xF4A261  # a sandy orange, as on a web page
red = (colour >> 16) & 0xFF
green = (colour >> 8) & 0xFF
blue = colour & 0xFF
print("red", red, "green", green, "blue", blue)
print(hex((red << 16) | (green << 8) | blue))
Listing 3.6. Masks on a byte of flags, and the three bytes of a colour. code/grade-10/03-machine-integers/listings/masks.py
$ python masks.py
10100110 bit 2 is 1
10100111 after setting bit 0
10000110 after clearing bit 5
01011001 after flipping every bit
red 244 green 162 blue 97
0xf4a261
Output 3.6. format(x, "08b") writes x in binary on eight digits. The colour splits into three bytes, and the three bytes give the colour back.

A colour on a screen is often stored as 2424 bits, one byte for each of red, green and blue (Book 1 showed the #F4A261 notation of web pages). A shift moves the wanted byte to the right end, and the mask 0xFF, eight 11 bits, keeps that byte alone.

The colour 0xF4A261 as three bytes. Red is (c >> 16) & 0xFF, green (c >> 8) & 0xFF, blue c & 0xFF.
The colour 0xF4A261 as three bytes. Red is (c >> 16) & 0xFF, green (c >> 8) & 0xFF, blue c & 0xFF.

Method 3.12 (Testing, setting and clearing bit ii)

  1. Test: (x >> i) & 1 is 11 when bit ii of x is 11.
  2. Set to 11: x | (1 << i).
  3. Clear to 00: x & ~(1 << i).
  4. Flip: x ^ (1 << i).

3.4 Integers that never overflow

Python hides all of this: its integers have unlimited precision. When a result does not fit in a machine word, Python uses as many words as needed, at the price of slower arithmetic on very large numbers.

import math

print(2**100)
print(math.factorial(30))
print((2**100).bit_length(), math.factorial(30).bit_length())
print(2**63 - 1 + 1)
Listing 3.7. Large integers in Python. code/grade-10/03-machine-integers/listings/big_int.py
$ python big_int.py
1267650600228229401496703205376
265252859812191058636308480000000
101 108
9223372036854775808
Output 3.7. 21002^{100} needs 101101 bits; the last line goes past the largest signed 6464-bit integer without any trouble.

In practice — Fixed widths in other languages

Most other languages, among them C, C++, Rust and Java, use the processor’s fixed widths. The C type int32_t, for instance, is a signed integer of exactly 3232 bits; adding 11 to the largest one is an error that the program may not notice. When code in those languages computes with large values (money in cents, times in microseconds, file sizes), the first question is always: how many bits does the largest value need? The university books meet these types.

History — The year 2038

Many systems count time as a number of seconds since an instant called the Epoch, fixed by the POSIX standard at 1 January 1970, 00:00:00 UTC, every day counting exactly 86,40086{,}400 seconds. A count of seconds kept in a signed 3232-bit integer runs out in 2038, and the weekend problem computes the exact second. Software written to count in 6464 bits does not have the problem; old devices and old file formats that store 3232 bits do, which is why the date is known as the year 2038 problem.

3.5 Exercises

Exercise 3.1 ★

What do bin(13), hex(255), int("1010", 2), int("ff", 16) and bin(2**8) return?

Solution

Solution of Exercise 3.1.

(Python prints them with single quotes.) "0b1101", "0xff", 10, 255 and "0b100000000" (28=2562^8 = 256 needs nine bits).

Exercise 3.2 ★

A sensor sends its readings as 1212-bit unsigned integers. What are the smallest and the largest values? How many different values can it send?

Solution

Solution of Exercise 3.2.

From 00 to 212−1=40952^{12} - 1 = 4095: 40964096 different values.

Exercise 3.3 ★

Write −5-5, −1-1, −128-128 and 127127 in two’s complement on 88 bits. Which of 128128 and −129-129 can be written, and why?

Solution

Solution of Exercise 3.3.

−5-5 is 11111011 (see the example of the chapter), −1-1 is 11111111, −128-128 is 10000000, 127127 is 01111111. Neither 128128 nor −129-129 can be written: the range on 88 bits is −128-128 to 127127.

Exercise 3.4 ★

What do 1 << 10, 100 >> 2, 7 >> 3, 5 << 1 and 0b1011 >> 1 give? Say each time which multiplication or division by a power of two it computes.

Solution

Solution of Exercise 3.4.

1 << 10 is 1024=1×2101024 = 1 \times 2^{10}; 100 >> 2 is 2525, the quotient of 100100 by 44; 7 >> 3 is 00, the quotient of 77 by 88; 5 << 1 is 10=5×210 = 5 \times 2; 0b1011 >> 1 is 0b101, that is 55, the quotient of 1111 by 22.

Exercise 3.5 ★

Without looking at the chapter’s listing, write to_base(n, b) with its docstring and test it by converting back with int. What does it return for n=0n = 0, and why must that case be treated apart?

Solution

Solution of Exercise 3.5.

The function of the chapter’s listing. For n=0n = 0 it returns "0"; without the special case, the loop while n > 0 would not run and the function would return the empty string, which is not a way of writing a number. The test: int(to_base(n, b), b) == n for many n and b (the chapter’s tests try 500500).

Exercise 3.6 ★★

Without computing the product, give the largest number of bits that the product of a 2020-bit number and a 1313-bit number can need, and the smallest. Give an example for each.

Solution

Solution of Exercise 3.6.

At most 20+13=3320 + 13 = 33 bits, by the proposition on the bits of a product; the largest numbers on 2020 and 1313 bits reach it, as the listing printed. At least 3232 bits: a 2020-bit number is at least 2192^{19} and a 1313-bit number at least 2122^{12}, so the product is at least 2312^{31}, which needs 3232 bits; 219×2122^{19} \times 2^{12} is an example.

Exercise 3.7 ★★

A program reads 8-bit two’s-complement values from a file as strings of eight characters 0 and 1, and decodes them with int(bits, 2). A temperature of −5-5 degrees appears as 251251. Explain the bug and write a correct decode(bits).

Solution

Solution of Exercise 3.7.

int(bits, 2) gives the leftmost bit the weight +128+128 instead of −128-128, that is, it returns the unsigned reading, which is 256256 too large for a negative value: −5+256=251-5 + 256 = 251. A correct decoder subtracts 282^8 when the sign bit is 11: u = int(bits, 2), then return u - 2**len(bits) if bits[0] == "1" else u (exercises/decode_bug.py).

Exercise 3.8 ★★

Write test_bit(x, i), set_bit(x, i) and clear_bit(x, i), and test that clearing a bit after setting it gives the same result as clearing it directly.

Solution

Solution of Exercise 3.8.

The three functions of the method box (exercises/bit_ops.py): (x >> i) & 1 == 1, x | (1 << i) and x & ~(1 << i). Clearing after setting gives the same result as clearing directly, since the clear decides bit i alone and setting changed no other bit; the chapter’s tests check it on 300300 random pairs.

Exercise 3.9 ★★

On 88 bits, compute 100+50100 + 50: the pattern of the result, its unsigned value and its signed value. Which of the two readings overflows? Do the same for −100+(−50)-100 + (-50).

Solution

Solution of Exercise 3.9.

100+50=150100 + 50 = 150: the pattern is 10010110. Its unsigned value is 150150, which fits (no carry); its signed value is 150−256=−106150 - 256 = -106: the signed reading overflows. For −100+(−50)-100 + (-50), the patterns are 156156 and 206206, whose sum 362362 leaves the pattern 362−256=106362 - 256 = 106, 01101010: the unsigned addition carries, and the signed result reads 106106 instead of −150-150, so both readings overflow.

Exercise 3.10 ★★

Follow the values of a and b through a = a ^ b, b = a ^ b, a = a ^ b, starting with a = 12 and b = 10, in binary. What do the three lines do? Use the facts x ^ x == 0 and x ^ 0 == x to explain why.

Solution

Solution of Exercise 3.10.

a = 1100, b = 1010. After the first line a = 0110; after the second b = 0110 ^ 1010 = 1100; after the third a = 0110 ^ 1100 = 1010. Now a is 1010 and b is 1212: the values are swapped. With a0a_0, b0b_0 the starting values, the second line computes (a0⊕b0)⊕b0=a0⊕0=a0(a_0 \oplus b_0) \oplus b_0 = a_0 \oplus 0 = a_0, and the third (a0⊕b0)⊕a0=b0(a_0 \oplus b_0) \oplus a_0 = b_0, writing ⊕\oplus for xor (it can be computed in any order, as one checks bit by bit).

Exercise 3.11 ★★

To read the green byte of a colour, a student writes (c >> 16) & 0xFF; another writes c >> 8. For c = 0xF4A261, what does each get? Correct both.

Solution

Solution of Exercise 3.11.

(c >> 16) & 0xFF is 0xF4 =244= 244, the red byte. c >> 8 is 0xF4A2 =62,626= 62{,}626, the red and green bytes together. Green is (c >> 8) & 0xFF =162= 162: shift by one byte, then keep one byte.

Exercise 3.12 ★★★

Prove that for every signed nn-bit integer xx other than −2n−1-2^{n-1}, flipping the bits of xx and adding 11 gives the pattern of −x-x, and say what happens for −2n−1-2^{n-1} (try it on 44 bits).

Solution

Solution of Exercise 3.12.

Let uu be the unsigned reading of xx and uˉ\bar u that of the flipped pattern. In each column one of the two has a 11, so u+uˉ=2n−1u + \bar u = 2^n - 1 and uˉ+1=2n−u\bar u + 1 = 2^n - u. If x≥0x \ge 0 then u=xu = x and 2n−x2^n - x is the pattern of −x-x (for x=0x = 0 it is 2n2^n, which keeps nn bits as 00). If x<0x < 0 then u=x+2nu = x + 2^n and 2n−u=−x2^n - u = -x, which is positive and in range as long as x≠−2n−1x \ne -2^{n-1}. For x=−2n−1x = -2^{n-1} (on 44 bits, 1000, that is −8-8), flipping gives 0111 and adding 11 gives 1000 again: −(−8)=8-(-8) = 8 is out of range, and the negation overflows back to −8-8.

Exercise 3.13 ★★★

The population count of x≥0x \ge 0 is the number of 11 bits of xx. Write a function that looks at the bits one by one with x & 1 and x >> 1, and a second one that repeats x = x & (x - 1) until xx is 00. Explain why x & (x - 1) clears the rightmost 11 bit, and compare the numbers of loop turns of the two functions for x=240x = 2^{40}.

Solution

Solution of Exercise 3.13.

Subtracting 11 turns the rightmost 11 bit of xx into 00 and the 00 bits to its right into 11; the bits further left do not change. The and with xx keeps those left bits and clears all the others, that is, it clears exactly the rightmost 11. So the second function turns its loop once per 11 bit, while the first turns once per bit of xx (x.bit_length() times). For x=240x = 2^{40}: 4141 turns against 11 (exercises/popcount.py).

Exercise 3.14 ★★★

Prove the proposition on detecting a signed overflow: if xx and yy have different signs, x+yx + y is always in range; if both are ≥0\ge 0 and the true sum is too large, the stored result has its sign bit set; if both are negative and the true sum is too small, it has its sign bit clear.

Solution

Solution of Exercise 3.14.

If x≥0>yx \ge 0 > y, then y≤x+y<xy \le x + y < x, so the sum lies between two numbers in range and is in range. If both are ≥0\ge 0, the true sum is at most 2(2n−1−1)=2n−22(2^{n-1} - 1) = 2^n - 2; when it is too large, it lies from 2n−12^{n-1} to 2n−22^n - 2, fits in nn unsigned bits, and its bit n−1n-1 is 11: the stored result reads as negative. If both are negative, the true sum is at least −2n-2^n; when it is too small, it lies from −2n-2^n to −2n−1−1-2^{n-1} - 1, and the stored pattern, the true sum plus 2n2^n, lies from 00 to 2n−1−12^{n-1} - 1: its sign bit is 00. Conversely, when there is no overflow the result has the sign of two operands of the same sign.

Exercise 3.15 ★★★

Write add_n_bits(a, b, n), which adds two nn-bit patterns and returns the nn-bit result, the carry (the unsigned sum needed n+1n + 1 bits) and the signed overflow flag. Test it against Python’s own arithmetic for every pair of 88-bit values you can afford, and give the result for (100, 50, 8).

Solution

Solution of Exercise 3.15.

The file exercises/add_n_bits.py computes total = a + b, result = total % 2**n, carry = total >= 2**n, and with sign = 2**(n - 1), the overflow flag is true when a & sign == b & sign and result & sign != a & sign (the proposition proved in the previous exercise). The tests compare it with Python’s arithmetic on 256×37256 \times 37 pairs of 88-bit values. add_n_bits(100, 50, 8) returns (150, False, True).

3.6 Problem: The 2038 Rollover

Problem 3.1

Weekend problem — the last second of a 32-bit clock

A door-entry system records the time of each badge as the number of seconds since 1 January 1970, 00:00:00 UTC (see the history box of this chapter), in a signed 3232-bit integer. The program exercises/rollover.py and Python’s datetime module help with the dates, but every count below can be done by hand first.

Part I — Counting seconds.

  1. How many seconds are there in a day, and in a year of 365365 days?
  2. How many days are there from 1 January 1970 to 1 January 2000? (There are 77 leap years among 1970–1999; name them.)
  3. Deduce the number of seconds since the Epoch at 1 January 2000, 00:00:00 UTC.
  4. Check it with Python: datetime(2000, 1, 1, tzinfo=UTC).timestamp(), after from datetime import UTC, datetime.

Part II — The largest value.

  1. What is the largest signed 3232-bit integer? Give it as a power of two minus one and in decimal.
  2. Write its pattern in hexadecimal.
  3. About how many years of 365.25365.25 days does it represent?
  4. Add that to 1970: in which year does the counter run out?

Part III — The exact instant.

  1. Run exercises/rollover.py. At which date and time does the largest value fall?
  2. How many whole days after the Epoch is that, and how many seconds remain after those days?
  3. Convert the remaining seconds into hours, minutes and seconds, and check the time printed by the program.
  4. What is the next second, written as a count, and why can the register not hold it?

Part IV — After the wrap.

  1. Adding 11 to the largest value in a signed 3232-bit register gives which pattern, and which signed value?
  2. Using the wheel of this chapter, explain the jump on a 44-bit clock that counts from 00.
  3. Which date does the program print for the wrapped value?
  4. By how many seconds does the clock jump backwards? Express it as a power of two.
  5. How long before 1970 is the wrapped date, in days? Check with the answer to question 10.
  6. If the count were stored as an unsigned 3232-bit integer instead, when would it run out? (The program prints it.) What would the system then be unable to record?
  7. With 6464 signed bits, how long would the count last? (The program prints it.)
  8. State the result: the last instant a signed 3232-bit count of seconds can hold, and the date it shows one second later.
Solution

Solution of Problem 3.1.

1. 24×3600=86,40024 \times 3600 = 86{,}400 seconds in a day; 365×86,400=31,536,000365 \times 86{,}400 = 31{,}536{,}000 in a year of 365365 days.

2. The leap years are 1972, 1976, 1980, 1984, 1988, 1992 and 1996: 30×365+7=10,95730 \times 365 + 7 = 10{,}957 days.

3. 10,957×86,400=946,684,80010{,}957 \times 86{,}400 = 946{,}684{,}800 seconds.

4. Python prints 946684800.0.

5. 231−1=2,147,483,6472^{31} - 1 = 2{,}147{,}483{,}647.

6. 0x7FFFFFFF: a 00 sign bit followed by 3131 ones.

7. A year of 365.25365.25 days lasts 31,557,60031{,}557{,}600 seconds; 2,147,483,647/31,557,600≈68.052{,}147{,}483{,}647 / 31{,}557{,}600 \approx 68.05 years.

8. 1970+68=20381970 + 68 = 2038.

9. 19 January 2038, 03:14:07 UTC.

10. 2,147,483,647=24,855×86,400+11,6472{,}147{,}483{,}647 = 24{,}855 \times 86{,}400 + 11{,}647: 24,85524{,}855 whole days and 11,64711{,}647 seconds.

11. 11,647=3×3600+14×60+711{,}647 = 3 \times 3600 + 14 \times 60 + 7: 03:14:07, as printed.

12. 231=2,147,483,6482^{31} = 2{,}147{,}483{,}648, one more than the largest signed 3232-bit integer.

13. The pattern written 0x80000000 in hexadecimal, a 11 followed by 3131 zeros, whose signed value is −231=−2,147,483,648-2^{31} = -2{,}147{,}483{,}648.

14. On the 44-bit wheel, the clock counts 0,1,…,70, 1, \dots, 7, then the next step lands on −8-8: it jumps from the largest value to the smallest.

15. 13 December 1901, 20:45:52 UTC.

16. The register holds −231-2^{31} instead of 2312^{31}: the clock is 232=4,294,967,2962^{32} = 4{,}294{,}967{,}296 seconds behind the true time.

17. 231=24,855×86,400+11,6482^{31} = 24{,}855 \times 86{,}400 + 11{,}648, one second more than in question 10. Going back 24,85524{,}855 days from 1 January 1970 reaches 14 December 1901, 00:00:00, and going back 11,64811{,}648 seconds more, that is 3 h 14 min 8 s, reaches 13 December 1901, 20:45:52.

18. At 232−12^{32} - 1 seconds: 7 February 2106, 06:28:15 UTC. An unsigned count cannot hold any negative value, so it could not record a date before 1970.

19. About 292292 billion years.

20. A signed 3232-bit count of seconds since 1 January 1970 holds its last value, 231−12^{31} - 1, at 19 January 2038, 03:14:07 UTC; one second later it wraps to −231-2^{31}, which reads as 13 December 1901, 20:45:52 UTC.

এই অধ্যায়ে সংজ্ঞায়িত পরিভাষা-শব্দ

পরিভাষায় সব 1050 টি শব্দ দেখো