Search code examples
clogicbit-manipulation

Determine the sign of a 32 bit int


Using ONLY:

! ~ & ^ | + << >>

NO LOOPS

I need to determine the sign of a 32 bit integer and I need to return 1 if positive, 0 if 0 and -1 if negative.

Any ideas? I first thought about shifting over 31 bits and then looking at that sign but that obviously wont work and now I am kind of stuck.


Solution

  • Try this:

    (x >> 31) | (((0 - x) >> 31) & 1)
    

    How about this:

    (x >> 31) | (((~x + 1) >> 31) & 1)
    

    EDIT 2:

    In response to issues (or rather nit-picking) raised in the comments...

    Assumptions for these solutions to be valid:

    1. x is of type 32-bit signed integer.
    2. On this system, signed 32-bit integers are two's complement. (right-shift is arithmetic)
    3. Wrap-around on arithmetic overflow.
    4. For the first solution, the literal 0 is the same type as x.