Determine the sign of a 32 bit int

后端 未结 8 1515
隐瞒了意图╮
隐瞒了意图╮ 2021-02-08 23:05

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:26

    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.

提交回复
热议问题