Determine the sign of a 32 bit int

2020-06-03 07:26发布

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.

8条回答
贪生不怕死
2楼-- · 2020-06-03 07:52

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);
}
查看更多
唯我独甜
3楼-- · 2020-06-03 08:01

A bit more convoluted, but there is this:

(~((x >> 31) & 1) + 1) | (((~x + 1) >> 31) & 1)

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:

(z >> 31) & 1

Will result in a 1 when negative, and a 0 otherwise.

Any place we have:

(~z + 1)

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.

查看更多
登录 后发表回答