Bit wise | OR operation in C++: Explained with program and Truth table.


Overview:


The | (bitwise OR) in C or C++ takes two numbers as operands and does OR on every bit of two numbers. The result of OR is 1 if any of the two bits is 1.


| - bitwise OR :

OR gate:

Truth table :

INPUT 1

INPUT 2

OUTPUT

A

B

A+B

0

0

0

0

1

1

1

0

1

1

1

1


Sample C++ program using : OR gate :
 
Example 1: 
 
#include <iostream>
#include<stdio.h>
int a=5; //binary = 0101
int b=12; //binary =1100

int main() {
std::cout << (a|b); //output will be=13 binary --> 1101

return 0;
}
 

 

Example 2:

 

#include <iostream>
using namespace std;
int main() {
 
int a = 5;// 0101b
 
int b = 12;// 1100b
 
int c = a | b; // 1101b
 
std::cout << "a = " << a << ", b = " << b << ", c = " << c << std::endl;
 
return 0;
}


When the binary value for a ( 0101 ) and the binary value for b ( 1100 ) are OR 'ed together we get the binary value of
1101 :
int a = 0 1 0 1
int b = 1 1 0 0
---------
int c = 1 1 0 1


Decimal to Binary conversion :

 

Step 1: Divide the given decimal number by 2 and note down the remainder.
Step 2: Now, divide the obtained quotient by 2, and note the remainder again.
Step 3: Repeat the above steps until you get 0 as the quotient.
Step 4: Now, write the remainders in such a way that the last remainder is written first, followed by the rest in the reverse order.

 

Example :

Lets take the decimal number 13 :

 

 13÷2 = 6 ---> Reminder ---> 1

 6÷2   = 3 ---> Reminder ---> 0

 3÷2   = 1 ---> Reminder ---> 1

 1÷2   = 0 ---> Reminder ---> 1

 

13 in binary = 1101

 

 

Binary to Decimal conversion :

Converting number : 11000100 

  =196

Decimal to Binary Table :

 

Decimal Numbers

Binary Numbers

0

0

1

1

2

10

3

11

4

100

5

101

6

110

7

111

8

1000

9

1001

10

1010

11

1011

12

1100

13

1101

14

1110

15

1111