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 negative.
Any ideas? I first thought about shifting over 31 bits and then looking at that sign but that obviously wont work and now I am kind of stuck.
Why do you need to use bitwise operators for that?
If you absolutely have to use bitwise operators, then you can use the
&
operator to check for negative values, no shifting needed:If you want to shift:
A bit more convoluted, but there is this:
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:
Will result in a 1 when negative, and a 0 otherwise.
Any place we have:
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.