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
Assuming the implementation defines arithmetic right shift:
(x>>31) | !!x
Unlike Mystical's answer, there is no UB.
And, if you want to also support systems where right shift is defined to be arithmetic shift:
~!(x>>31)+1 | !!x
Edit: Sorry, I omitted a !
in the second version. It should be:
~!!(x>>31)+1 | !!x
This version is still dependent on the implementation being twos complement and having either arithmetic or logical right-shift, i.e. if the implementation-defined behavior were something else entirely it could break. However, if you change the types to unsigned types, all of the implementation-defined behavior vanishes and the result is -1U
, 0U
, or 1U
depending on the "sign" (high bit and zero/nonzero status) of x
.