Note: isgreater(a, b) cannot return 1 when a == b. Which means ispositive(0) cannot return 1. So make isgreater(a, b) return 1 if a > b and 0 for a <= b by making ispositive(x) return 1 if x > 0 and 0 if x <= 0 and issamesign(a, b) return 1 when a and b are +ve or -ve and neither is 0 (same for isdiffsign(a, b)) and add special cases when either a or b is 0.
int compare(a, b):
return
(+1 * isgreater(a, b)) +
(-1 * isgreater(b, a))
//returns 1 if a > b, 0 if a <= b
bit isgreater(a, b):
return
// ++ or --
(issamesign(a, b) & ispositive(a-b)) +
// +- or -+
(isdiffsign(a, b) & ispositive(a)) +
// 0-
(iszero(a) & isnegative(b)) +
// +0
(ispositive(a) & iszero(b))
// returns 1 if ++ or --, 0 if either is 0
bit issamesign(a, b):
return
(ispositive(a) & ispositive(b)) |
(isnegative(a) & isnegative(b))
// returns 1 if +- or -+, 0 if either is 0
bit isdiffsign(a, b):
return
(ispositive(a) & isnegative(b)) |
(isnegative(a) & ispositive(b))
// returns 1 if +, 0 if 0
bit ispositive(x):
return (msb(x) ^1) * isnotzero(x)
// returns 1 if -, 0 if 0
bit isnegative(x):
return msb(x)
bit isnotzero(x):
return msb(x | -x)
bit msb(x):
return (x >>31) &1
Instead of a mutually exclusive implementation of ispositive(x) for +ve and 0, since isnegative(x) is mutually exclusive (1 only if -ve), it suffices for a mutually exclusive implementation of isgreater(a, b) where a is greater if same signs and b-a is negative OR diff signs and b is negative.
int compare(a, b):
isgreater(a, b) * +1 +
isgreater(b, a) * -1
// 1 if a > b, 0 if a <= b
bit isgreater(a, b):
return
issamesign(a, b) * isnegative(b-a) |
isdiffsign(a, b) * isnegative(b)
bit issamesign(a, b):
return toggle(isdiffsign(a, b))
bit isdiffsign(a, b):
return msb(a ^ b)
// 1 if neg, 0 if >= 0
bit isnegative(x):
return msb(x)
bit toggle(x):
bit msb(x):
bit lsb(x):
No comments:
Post a Comment