[Operating System] Integer Overflow

tl;dr

For unsigned numbers, any addition that produces an extra bit is a problem.

For 2C signed numbers, sometimes addition or subtraction produces an additional bit. This is not necessarily a problem. Arithmetic overflow can occur when you are adding two positive or two negative numbers - in this case if the sign of the result is different from the sign of the addends you have an overflow (if you add two positive numbers and get a negative result; if you add two negative numbers and get a positive result).

========================================================================

In mathematics, integers have infinite width. There are an infinite number of them. But in computer hardware, integers have finite width. The width is defined by the hardware's architecture and limited by hardware circuits themselves. Nowadays computers can support 64-bit integers, which gives you a total of 2^64 integers.

Integer overflow happens when operation result is outside the integer's range.


If we use an n-bit storage location to store a unsigned number, we can store numbers between 0 and 2^n - 1 inclusive. If an operation result overflows, the extra bit will be discarded.

Two's complement (2C)

Two's complement is a binary representation designed to allow us to store and manipulate both positive and negative numbers. To represent a number x, we actually compute and store 2^n + x, but only keep the lower n bits of the result.

Example 4-bit 2C numbers:

10000 + 0101 (5) = 10101. 0101 (5) gets stored.
10000 - 0101 (-5) = 1011. 1011 (-5) gets stored.

For 2C numbers, all of the positive numbers have 0 in their most significant bits, and all of the negative numbers have 1. The range of an n-bit number is -2^(n - 1) through 2^(n - 1) - 1 (The most significant bit is used to store sign). The integer type in common programming languages is 32-bit 2C numbers (-2,147,483,648 through 2,147,483,647). The most negative number has no positive counterpart, because of 0.

Why 2C?

The 2C representation is convenient because it makes regular addition works for both positive and negative numbers:


Note that overflow is still a problem. It's possible to add two numbers such that the result does not fit in the 2C representation.
(With 2C, overflow isn't just when number is carried out past the most significant bit)

Comments

Popular posts from this blog

[LeetCode] 714. Best Time to Buy and Sell Stock with Transaction Fee

[LeetCode] 269. Alien Dictionary

[LeetCode] 631. Design Excel Sum Formula