
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
Check if a number is positive, negative or zero using bit operators in C++
Here we will check whether a number is positive, or negative or zero using bit operators. If we perform shifting like n >> 31, then it will convert every negative number to -1, every other number to 0. If we perform –n >> 31, then for positive number it will return -1. When we do for 0, then n >> 31, and –n >> 31, both returns 0. for that we will use another formula as below −
1+(𝑛>>31)−(−𝑛>>31)
So now, if
- n is negative: 1 + (-1) – 0 = 0
- n is positive: 1 + 0 – (-1) = 2
- n is 0: 1 + 0 – 0 = 1
Example
#include <iostream> #include <cmath> using namespace std; int checkNumber(int n){ return 1+(n >> 31) - (-n >> 31); } int printNumberType(int n){ int res = checkNumber(n); if(res == 0) cout << n << " is negative"<< endl; else if(res == 1) cout << n << " is Zero" << endl; else if(res == 2) cout << n << " is Positive" << endl; } int main() { printNumberType(50); printNumberType(-10); printNumberType(70); printNumberType(0); }
Output
50 is Positive -10 is negative 70 is Positive 0 is Zero
- Related Articles
- How to check if a number is positive, negative or zero using Python?
- C program to Check Whether a Number is Positive or Negative or Zero?
- C# Program to check if a number is Positive, Negative, Odd, Even, Zero
- Program to check if a number is Positive, Negative, Odd, Even, Zero?
- What is zero if it is not a negative or positive number?
- C++ Program to Check Whether a Number is Positive or Negative
- Python Program to Check if a Number is Positive, Negative or 0
- How to check whether a number is Positive or Negative in Golang?
- Java Program to Check Whether a Number is Positive or Negative
- Haskell Program to Check Whether a Number is Positive or Negative
- Check whether product of integers from a to b is positive, negative or zero in Python
- Why is there no zero positive and negative number?
- Check if a number is multiple of 5 without using / and % operators in C++
- Java program to find if the given number is positive or negative
- Java Menu Driven Program to Check Positive Negative or Odd Even Number

Advertisements