Determine the sign of a 32 bit int

后端 未结 8 2082
天涯浪人
天涯浪人 2021-02-08 22:38

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 ne

8条回答
  •  长发绾君心
    2021-02-08 23:11

    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.

提交回复
热议问题