Until it is simply the way things are

The Legal Gender Recognition in the Philippines: A Legal and Policy Review produced as part of UNDP’s Being LGBTI in Asia Programme is a one of those milestone knowledge products worth holding in…

Smartphone

独家优惠奖金 100% 高达 1 BTC + 180 免费旋转




Integer Overflow

Have you ever encountered a situation where adding two positive numbers resulted in a negative number or vice versa? You see such ridiculous results when an overflow occurs with arithmetic operations. That is when the result of an arithmetic operation cannot be contained within the word size of the data type.

Let’s get this clarified with a few examples.

Let’s say that we have two 4-bit numbers, 12 (in binary 1100) and 7 (in binary 0111). Sum of these two numbers, 12+7 = 19 (in binary 10011) needs 5 bits to represent the result. If we truncate the bits with weight greater than 2³ that is if we discard the higher order bit, we are left with 0011 which is 3. This is actually equivalent to the value 19 mod 16 = 3.

In C and Java, overflows are not considered as errors.

Since both the positive and negative numbers can be represented with two’s complement, we have to decide what to do when the resulting value of a two’s complement addition becomes too large or too small to represent with a given number of bits. As we have seen here, with w bits,

When a sum of two numbers exceeds the max value, we call that a positive overflow and when the result is less than min value, we call it a negative overflow. Let’s see this in action with 4-bits.

The maximum positive value that can be represented with 4 bits in two’s complement representation is 7 and the minimum value is -8. Following table shows two examples of overflow scenarios.

Just like with addition, in multiplication also we have to deal with overflow scenarios. For example with 4-bits to represent numbers 4 (in binary 0100) and 5(in binary 0101), multiplication (expected value 20[in binary 10100]) gives 4 (in binary 0100) as the result. This is equivalent to, 4.5 mod 2⁴ = 20 mod 16 = 4.

With two’s complement numbers, we can derive the multiplication result in following two steps.

Let’s say we have two numbers x and y each with w-bits, then

Add a comment

Related posts:

Forgotten

Storytelling has never been one of my strengths. I consider the wicked truths of the world beautiful because I myself am a wicked truth. Maybe it was how my parents raised me or the trauma they…

Do I Look Fat in This?

Dad came and got me out of the dog house earlier. I was glad, too, cuz Max is a great dog but his farts stink. Mom says they smell like rotten eggs. I didn’t exactly know how he knew where to find me…

Clean Architecture

O papel do desenvolvimento de software nas organizações ganhou um espaço fundamental no seu bom funcionamento, para que o software não seja um empecilho durante seu uso, foi pensado formas de fazer…