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
Why do you need to use bitwise operators for that?
int get_sign(int value)
{
return (value < 0) ? -1 : (int)(value != 0);
}
If you absolutely have to use bitwise operators, then you can use the &
operator to check for negative values, no shifting needed:
int get_sign(int value)
{
return (value & 0x80000000) ? -1 : (int)(value != 0);
}
If you want to shift:
int get_sign(int value)
{
return ((value >> 31) & 1) ? -1 : (int)(value != 0);
}
Dimitri's idea could be simplified to (!!x) - ((x >> 30) & 2)
And just to give one more cryptic solution:
~!x & ((-((unsigned) x >> 31)) | !!x)