এই বইটি এখনো বাংলা ভাষায় পাওয়া যায় না। সংস্করণ: 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 , , or 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 with the digits and , each position worth twice the one on its right; in base with the digits to and to ; 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). , and (mathematics book, grade 8).
3.1 Unsigned integers on bits
Base is one base among many. In any base , a whole number is written with digits from to , and the digit at position (counting from on the right) is worth times its value. The digits are found from the right by repeated division: the remainder of divided by 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))
$ 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
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, -bit integer)
An -bit integer is a whole number stored in exactly bits, . Read as an unsigned integer, its value is . The usual sizes are bits (one byte), , and bits.
Proposition 3.2 (Range of bits)
The unsigned integers on bits are exactly the whole numbers from to . A whole number needs bits, where is the number with .
Proof. There are choices for each of the bits, so patterns, and different patterns have different values (base writing is unique). The smallest value is (all bits ). The largest has all bits : adding to carries through every column and gives , which is ; so is . Hence the values are . A number with fits in bits but not in , whose largest value is . ∎
So one byte holds to , bits hold to , and bits to .
Python’s method n.bit_length() gives the number of bits that 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")
$ 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
Proposition 3.3 (Bits of a sum and of a product)
If fits in bits and in bits, with , then fits in bits and fits in bits.
Proof. and , so . And . ∎
The run above shows that both bounds can be reached: the largest numbers on and bits have a sum of bits and a product of .
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 -bit unsigned adder then keeps the lowest bits of the true result, that is, the remainder of the true result divided by : the value wraps around.
Python’s % gives that remainder, so a few lines simulate the step counter, here with 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))
$ 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
The toy machine of the next year (grade 11) has registers of one byte. The same addition, , run on it:
LOADI R0, 250
ADDI R0, 10 ; 250 + 10 does not fit in one byte
HALT
$ 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
R0 holds , and the flag C (carry) is : 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 bits, the pattern stands for the signed value
The leftmost bit is the sign bit: it is exactly for the negative values.
The first half of the patterns, those starting with , keep their unsigned value; the second half stands for negative numbers. The listing prints the sixteen patterns of 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"))
$ 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
Proposition 3.6 (Range and negation)
The signed integers on bits are the whole numbers from to . The pattern of and its unsigned reading satisfy if and if . To negate a number, flip every bit and add (keeping bits).
Proof. If the sign bit is , the value is that of the other bits, from to . If it is , the value is plus a number from to , so from to ; and it is the unsigned value, which counts the leftmost bit as , minus . For the negation, write for the pattern with every bit of flipped. In each column exactly one of and has a , so the unsigned readings add up to . Hence , which on bits is the pattern of . ∎
Example 3.7 ( on 8 bits)
is 00000101; flipping every bit gives 11111010; adding gives 11111011. Check: .
The great advantage of two’s complement is that the addition does not change. Since a negative is stored as , and the adder works modulo , 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: on bits gives the pattern of , which reads as . This can be spotted without the true result.
Proposition 3.8 (Detecting a signed overflow)
The sum of two signed -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 where both a and b have a (and); a | b where at least one has a (or); a ^ b where exactly one has a (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 positions: a << k to the left, adding zeros on the right, and a >> k to the right, dropping the rightmost bits. For a whole number , a << k is 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 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 and clears the others; x | m sets them to ; x ^ m flips them. The mask 1 << i has a single , at position .
x (bits are numbered from on the right). The mask has a at position and 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))
$ 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
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 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 bits, keeps that byte alone.
0xF4A261 as three bytes. Red is (c >> 16) & 0xFF, green (c >> 8) & 0xFF, blue c & 0xFF.Method 3.12 (Testing, setting and clearing bit )
- Test:
(x >> i) & 1is when bit ofxis . - Set to :
x | (1 << i). - Clear to :
x & ~(1 << i). - 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)
$ python big_int.py
1267650600228229401496703205376
265252859812191058636308480000000
101 108
9223372036854775808
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 bits; adding 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 seconds. A count of seconds kept in a signed -bit integer runs out in 2038, and the weekend problem computes the exact second. Software written to count in bits does not have the problem; old devices and old file formats that store 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" ( needs nine bits).
Exercise 3.2 ★
A sensor sends its readings as -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 to : different values.
Exercise 3.3 ★
Write , , and in two’s complement on bits. Which of and can be written, and why?
Solution
Solution of Exercise 3.3.
is 11111011 (see the example of the chapter), is 11111111, is 10000000, is 01111111. Neither nor can be written: the range on bits is to .
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 ; 100 >> 2 is , the quotient of by ; 7 >> 3 is , the quotient of by ; 5 << 1 is ; 0b1011 >> 1 is 0b101, that is , the quotient of by .
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 , and why must that case be treated apart?
Solution
Solution of Exercise 3.5.
The function of the chapter’s listing. For 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 ).
Exercise 3.6 ★★
Without computing the product, give the largest number of bits that the product of a -bit number and a -bit number can need, and the smallest. Give an example for each.
Solution
Solution of Exercise 3.6.
At most bits, by the proposition on the bits of a product; the largest numbers on and bits reach it, as the listing printed. At least bits: a -bit number is at least and a -bit number at least , so the product is at least , which needs bits; 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 degrees appears as . Explain the bug and write a correct decode(bits).
Solution
Solution of Exercise 3.7.
int(bits, 2) gives the leftmost bit the weight instead of , that is, it returns the unsigned reading, which is too large for a negative value: . A correct decoder subtracts when the sign bit is : 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 random pairs.
Exercise 3.9 ★★
On bits, compute : the pattern of the result, its unsigned value and its signed value. Which of the two readings overflows? Do the same for .
Solution
Solution of Exercise 3.9.
: the pattern is 10010110. Its unsigned value is , which fits (no carry); its signed value is : the signed reading overflows. For , the patterns are and , whose sum leaves the pattern , 01101010: the unsigned addition carries, and the signed result reads instead of , 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 and b is : the values are swapped. With , the starting values, the second line computes , and the third , writing 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 , the red byte. c >> 8 is 0xF4A2 , the red and green bytes together. Green is (c >> 8) & 0xFF : shift by one byte, then keep one byte.
Exercise 3.12 ★★★
Prove that for every signed -bit integer other than , flipping the bits of and adding gives the pattern of , and say what happens for (try it on bits).
Solution
Solution of Exercise 3.12.
Let be the unsigned reading of and that of the flipped pattern. In each column one of the two has a , so and . If then and is the pattern of (for it is , which keeps bits as ). If then and , which is positive and in range as long as . For (on bits, 1000, that is ), flipping gives 0111 and adding gives 1000 again: is out of range, and the negation overflows back to .
Exercise 3.13 ★★★
The population count of is the number of bits of . 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 is . Explain why x & (x - 1) clears the rightmost bit, and compare the numbers of loop turns of the two functions for .
Solution
Solution of Exercise 3.13.
Subtracting turns the rightmost bit of into and the bits to its right into ; the bits further left do not change. The and with keeps those left bits and clears all the others, that is, it clears exactly the rightmost . So the second function turns its loop once per bit, while the first turns once per bit of (x.bit_length() times). For : turns against (exercises/popcount.py).
Exercise 3.14 ★★★
Prove the proposition on detecting a signed overflow: if and have different signs, is always in range; if both are 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 , then , so the sum lies between two numbers in range and is in range. If both are , the true sum is at most ; when it is too large, it lies from to , fits in unsigned bits, and its bit is : the stored result reads as negative. If both are negative, the true sum is at least ; when it is too small, it lies from to , and the stored pattern, the true sum plus , lies from to : its sign bit is . 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 -bit patterns and returns the -bit result, the carry (the unsigned sum needed bits) and the signed overflow flag. Test it against Python’s own arithmetic for every pair of -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 pairs of -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 -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.
- How many seconds are there in a day, and in a year of days?
- How many days are there from 1 January 1970 to 1 January 2000? (There are leap years among 1970–1999; name them.)
- Deduce the number of seconds since the Epoch at 1 January 2000, 00:00:00 UTC.
- Check it with Python:
datetime(2000, 1, 1, tzinfo=UTC).timestamp(), afterfrom datetime import UTC, datetime.
Part II — The largest value.
- What is the largest signed -bit integer? Give it as a power of two minus one and in decimal.
- Write its pattern in hexadecimal.
- About how many years of days does it represent?
- Add that to 1970: in which year does the counter run out?
Part III — The exact instant.
- Run
exercises/rollover.py. At which date and time does the largest value fall? - How many whole days after the Epoch is that, and how many seconds remain after those days?
- Convert the remaining seconds into hours, minutes and seconds, and check the time printed by the program.
- What is the next second, written as a count, and why can the register not hold it?
Part IV — After the wrap.
- Adding to the largest value in a signed -bit register gives which pattern, and which signed value?
- Using the wheel of this chapter, explain the jump on a -bit clock that counts from .
- Which date does the program print for the wrapped value?
- By how many seconds does the clock jump backwards? Express it as a power of two.
- How long before 1970 is the wrapped date, in days? Check with the answer to question 10.
- If the count were stored as an unsigned -bit integer instead, when would it run out? (The program prints it.) What would the system then be unable to record?
- With signed bits, how long would the count last? (The program prints it.)
- State the result: the last instant a signed -bit count of seconds can hold, and the date it shows one second later.
Solution
Solution of Problem 3.1.
1. seconds in a day; in a year of days.
2. The leap years are 1972, 1976, 1980, 1984, 1988, 1992 and 1996: days.
3. seconds.
4. Python prints 946684800.0.
5. .
6. 0x7FFFFFFF: a sign bit followed by ones.
7. A year of days lasts seconds; years.
8. .
9. 19 January 2038, 03:14:07 UTC.
10. : whole days and seconds.
11. : 03:14:07, as printed.
12. , one more than the largest signed -bit integer.
13. The pattern written 0x80000000 in hexadecimal, a followed by zeros, whose signed value is .
14. On the -bit wheel, the clock counts , then the next step lands on : it jumps from the largest value to the smallest.
15. 13 December 1901, 20:45:52 UTC.
16. The register holds instead of : the clock is seconds behind the true time.
17. , one second more than in question 10. Going back days from 1 January 1970 reaches 14 December 1901, 00:00:00, and going back seconds more, that is 3 h 14 min 8 s, reaches 13 December 1901, 20:45:52.
18. At 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 billion years.
20. A signed -bit count of seconds since 1 January 1970 holds its last value, , at 19 January 2038, 03:14:07 UTC; one second later it wraps to , which reads as 13 December 1901, 20:45:52 UTC.