Unfortunately, many of the answers above are incorrect. Let a 3-bit word be assumed:
unsigned: 4 5 6 7 0 1 2 3 == signed: -4 -3 -2 -1 0 1 2 3 (bit: 100 101 110 111 000 001 010 011)
Paul R's method is incorrect. Suppose we want to know if 3> 2. min (3,2) == 2, which says yes, so the method works here. Now suppose we want to know if 7> 2. The value 7 is -1 in the signed view, therefore min (-1,2) == -1, which mistakenly assumes that 7 does not exceed 2 unsigned.
Andrey’s method is also incorrect. Suppose we want to know that 7> 2, or = 7, and b = 2. The value 7 is -1 in the signed view, so the first member (a> b) fails, and the method assumes that 7 is no more than 2.
However, the BJobnh method corrected by Alexei is correct. Just subtract 2 ^ (n-1) from the values, where n is the number of bits. In this case, we would subtract 4 to get the new corresponding values:
old signed: -4 -3 -2 -1 0 1 2 3 => new signed: 0 1 2 3 -4 -3 -2 -1 == new unsigned 0 1 2 3 4 5 6 7.
In other words, unsigned_greater_than (a, b) is equivalent to sign_greater_than (a - 2 ^ (n-1), b - 2 ^ (n-1)).
T wu
source share