Alex Rivera | Logout

Check if a number is non zero using bitwise operators in C

Asked 2010-10-12T06:18:34.247
27

Check whether a number x is nonzero using the legal operators except !.

Examples: isNonZero(3) = 1, isNonZero(0) = 0

Legal ops: ~ & ^ | + << >>

  • Note : Only bitwise operators should be used. if, else, for, etc. cannot be used.
  • Edit1 : No. of operators should not exceed 10.
  • Edit2 : Consider size of int to be 4 bytes.

int isNonZero(int x) {
return ???;
}

Using ! this would be trivial , but how do we do it without using ! ?

Edit
Report

2 Answers

11
int isNonZero(unsigned x) {
    return ~( ~x & ( x + ~0 ) ) >> 31;
}

Assuming int is 32 bits (/* EDIT: this part no longer applies as I changed the parameter type to unsigned */ and that signed shifts behave exactly like unsigned ones).

answered 2010-10-12T07:34:09.027
-3

The following function example should work for you.

bool isNonZero(int x)
{
    return (x | 0);
}
answered 2012-06-13T19:49:46.560

Your Answer