A bit more confusing, but there is the following:
(~((x >> 31) & 1) + 1) | (((~x + 1) >> 31) & 1)
This should take care of the ambiguity of whether the shift will fill 1 or 0
For breakdown anywhere we have this design:
(z >> 31) & 1
The result will be 1 if negative, and 0 otherwise.
Any place with us:
(~z + 1)
We get a negative number (-z)
So, the first half will result in 0xFFFFFFFF (-1) if x is negative, and the second half will produce 0x00000001 (1) if x is positive. Then bitwise or together with them produce 0x00000000 (0), if none of them is true.
tdk001
source share