Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does an adder perform unsigned integer subtraction?

Suppose that A and B are signed positive integers, then for A-B, it's calculated using A+2's complement of B.

For example, in a 4-bit binary system, for signed integers, we have 7-3=0111-0011=0111+1101=(1)0100, the 1 in the bracket is the carry bit. According to the overflow rule for signed integer, we know there is no overflow and the result is therefore correct.

However, for unsigned integers, what will happen if we calculate 7-3? If we use the same way we mentioned above:

7-3=0111-0011=0111+1101=(1)0100

then, according to the overflow rule for unsigned integers, there is an overflow because of the carry out. In another word, 0100 is wrong because there is an overflow. But in fact, we know the result 0100 is correct.

If my analysis is correct, isn't it wrong to use adder to perform unsigned integer subtraction?

like image 909
JohnTang Avatar asked Nov 08 '11 15:11

JohnTang


1 Answers

Your analysis is not correct. Actually is CPU ALU unit dependent. :)

In first case you are using 4 bit integer but you forgotten that the highest bit of 4 bit sign integer is sign! So you are checking only the Carry and Overflow status and not also Negative status bit.

In generally binary arithmetic operations add and sub are the same for signed integers and unsigned integers. Only affected flags are different.

Actually you must consider:

  • at signed integer arithmetic Carry, Overflow and Negative flags.
  • at unsigned integer arithmetic only Carry flags.

Detail explanation:

The mining of complement function is negation, so to get opposite negative number from positive and positive from negative. We can make binary complement on two ways. Lets see both cases for number 3.

  1. At unsigned arithmetic is compl (3) = b'0011' xor b'1111' + b'0001' = b'1101' + Carry (Carry is set only at compl (0))
  2. At signed arithmetic numbers is comply (3) = b'10000' - b'0011' = b'1101' what is equal b'0000' - b'0011' = b'1101' + Carry (Carry is clear only at compl (0))

In first case function complement also complement the carry bit and we have also the second interpretation of carry flag named borrow.

In second case everything is clear. If we have got carry (overflow) at complement that mean that we need another overflow to normalize the result of subtraction.

like image 195
GJ. Avatar answered Nov 24 '22 06:11

GJ.