Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking whether a number is positive or negative using bitwise operators

I can check whether a number is odd/even using bitwise operators. Can I check whether a number is positive/zero/negative without using any conditional statements/operators like if/ternary etc.

Can the same be done using bitwise operators and some trick in C or in C++?

like image 622
Anirudhh Er Avatar asked Sep 23 '10 14:09

Anirudhh Er


People also ask

How do you check if a number is negative or positive?

If a number is greater than zero, it is a positive number. If a number is less than zero, it is a negative number. If a number equals to zero, it is zero.

Which bitwise operator can be used to check?

1. Using Bitwise XOR 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.

Which bit position is used to check if a value is negative?

For signed binary numbers the most significant bit (MSB) is used as the sign bit. If the sign bit is “0”, this means the number is positive in value. If the sign bit is “1”, then the number is negative in value.

Can bitwise and of two positive numbers be negative?

In general - Yes.


1 Answers

Can I check whether a number is positive/zero/negative without using any conditional statements/operators like if/ternary etc.

Of course:

bool is_positive = number > 0; bool is_negative = number < 0; bool is_zero = number == 0; 
like image 65
2 revs, 2 users 86% Avatar answered Oct 07 '22 19:10

2 revs, 2 users 86%