Search code examples
cbitsign

Check sign bit of 32 bit without using << or >>


I need a way to find the sign bit in a 32 bit integer (the most significant bit) using only the operators ! ~ & ^ | +. I am only allowed to use constants up to 0xFF, but larger numbers can be constructed. And it must be inline code, no loops or conditionals

Yes this is for an assignment however this is not the whole problem it is only a minor case I need to check.

I know I can get the sign by doing x>>31, which can be done using division, but that only leads to the need to have more bit shifts which i can't use :(

The fewer the operators the better too, because I am only allowed 10 to do the whole problem and this is only a minor case.

The problem this is for is to check if a number x is equal to 0x7FFFFFFF. the way my code reads now is [(is x neg?) & (is x+1 negative)]. if x equals 0x7FFFFFFF then adding 1 will overflow the buffer causing x to become negative. but this logic will only work if x is not negative before hand. hence the first part.

help me please???


Solution

  • Testing the sign bit is difficult; for the whole problem I think you're looking for something along the lines of

    !((~x) ^ (x + 1))
    

    This tests that ~x and x + 1 are bitwise identical i.e. are the same number.