Friday, July 01, 2016

compare bitwise

Return +1, 0, -1 for compare(a, b) with no comparison or if-else operator. Based on max bitwise.

Note: isgreater(a, b) cannot return 1 when a == b. Which means ispositive(0) cannot return 1. Without isnegative(x), isgreater(0, -1) returns 0 instead of 1.
// return +1, 0, -1
compare(a, b):
    return
    // a > b
    +1 * isgreater(a, b)
    + 
    // b > a
    -1 * islesser(a, b)

isgreater(a, b):
    return
    (ispositive(a-b) * issamesign(a, b) + 
    (ispositive(a) | isnegative(b)) * isdiffsign(a, b))

islesser(a, b):
    return
    (ispositive(b-a) * issamesign(a, b) + 
    (ispositive(b) | isnegative(a)) * isdiffsign(a, b))

isdiffsign(a, b): 
    return msb(a) ^ msb(b)
issamesign(a, b):
    return toggle(isdiffsign(a, b))

ispositive(x):
    return (msb(x) ^ 1) * isnotzero(x)
isnegative(x):
    return msb(x)
msb(x):
    return (x >> 31) & 1
lsb(x):
    return x & 1
toggle(bit):
    return lsb(bit) ^ 1

isnotzero(x):
    return msb(x | -x)

No comments:

Post a Comment