Determine the sign of a 32 bit int

后端 未结 8 2081
天涯浪人
天涯浪人 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:27

    A bit more convoluted, but there is this:

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

    This should take care of the ambiguity of whether the shift will fill in 1's or 0's

    For a breakdown, any place we have this construct:

    (z >> 31) & 1
    

    Will result in a 1 when negative, and a 0 otherwise.

    Any place we have:

    (~z + 1)
    

    We get the negated number (-z)

    So the first half will produce a result of 0xFFFFFFFF (-1) iff x is negative, and the second half will produce 0x00000001 (1) iff x is positive. Bitwise or'ing them together will then produce a 0x00000000 (0) if neither is true.

提交回复
热议问题