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.
I'm not sure this is the absolute ideal way to do things, but I think it's reasonably portable and at least somewhat simpler than what you had:
What about:
..for 32-bit signed int, 2's complement only.
!!n
gives 1 ifn
is nonzero.((n >> 30) & 2)
gives 2 iff the high bit (sign) is set. The bitwise NOT and +1 take the 2's complement of this, giving -2 or 0. Adding gives -1 (1 + -2) for negative values, 0 (0 + 0) for zero, and +1 (1 + 0) for positive values.Dimitri's idea could be simplified to (!!x) - ((x >> 30) & 2)
And just to give one more cryptic solution:
If conditionals (not
if
statements) and subtraction are allowed, the simplest & cleaner solution (IMO) is:Not using subtraction (and assuming
int
is 32 bits):Here's are the results:
Assuming the implementation defines arithmetic right shift:
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:
Edit: Sorry, I omitted a
!
in the second version. It should be: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
, or1U
depending on the "sign" (high bit and zero/nonzero status) ofx
.Try this:
How about this:
EDIT 2:
In response to issues (or rather nit-picking) raised in the comments...
Assumptions for these solutions to be valid:
0
is the same type as x.