Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a number x is positive (x>0) by ONLY using bitwise operators in C

isPositive - return true if x > 0, otherwise false

Example: isPositive(-1)

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

Max ops: 8

Note: No conditional statements are allowed.

inline bool isPositive(int32_t x) {
  return ???;
}
like image 485
Eternal Learner Avatar asked Oct 12 '10 07:10

Eternal Learner


People also ask

How XOR works on bitwise?

The Bitwise Xor operation treats the sign bit as it would any other bit. If one or both inputs for a pixel location are negative, the output is negative; if both inputs are positive, the output is positive.

How do you know if a number is a Bitwise operator?

The idea is to check whether the last bit of the number is set or not. If the last bit is set then the number is odd, otherwise even. As we know bitwise XOR Operation of the Number by 1 increment the value of the number by 1 if the number is even otherwise it decrements the value of the number by 1 if the value is odd.


2 Answers

int isPositive(int x) {
   return !((x&(1<<31)) | !x);
}

x&(1<<31 is to check if the number is negative.

!x is to check if the number is zero.

A number is positive if it's not negative and not zero.

like image 124
codaddict Avatar answered Nov 09 '22 19:11

codaddict


return !((x & 0x80000000) >> 31 | !x);
like image 20
Matthew Avatar answered Nov 09 '22 21:11

Matthew