In this post, we will learn how to find bitwise OR of two decimal numbers in C/C++.
The simplest way to find bitwise OR of two decimal numbers is to use bitwise OR ( | ) operator.
Syntax of bitwise OR operator
int a = 10;
int b = 30;
c = a | b;
The binary OR of a and b is in c.
#include<stdio.h>
int main() {
int a, b, c;
printf("Enter a: ");
scanf("%d", &a);
printf("Enter b: ");
scanf("%d", &b);
c = a | b;
printf("%d OR %d = %d", a, b, c);
}
Output
Enter a: 3
Enter b: 4
3 OR 4 = 7
Bitwise OR without using bitwise OR ( | ) operator
Now, you may need to calculate the bitwise OR of a number without using ‘|’. We will first convert the inputs to binary form and then OR the number using a loop.
Steps
- Let A and B be the input.
- Initialize 3 integer arrays – b1[], b2[], b3[] of size 64.
- Covert A to binary string and store the result in b1[].
- Convert B to binary string and store the result in b2[].
- Read each bit of b1[] and b2[] and perform bitwise OR. if anyone of b1[i] or b2[] is 1, then set b3[i] to 1. Otherwise, set b3[i] to 0.
- Convert b3[] to decimal and store the decimal value in an integer C.
- The bitwise OR of A and B is in C.
#include<stdio.h>
// converts binary string stored in b[]
// to decimal integer
int binary_to_decimal(int* b) {
int n = 0, i;
for (i = 63; i >= 0; --i) {
if (b[i] == 1) {
n = n * 2 + 1;
}
else {
n = n * 2;
}
}
return n;
}
// converts n to binary and store the binary
// string in b[]
// the least significant bit is at 0 position if b[]
void decimal_to_binary(int* b, int n) {
int r, i = 0;
while (n > 0) {
r = n % 2;
n = n / 2;
b[i] = r;
++i;
}
}
// return bitwise OR of a and b
int bitwiseOR(int a, int b) {
int c, i;
int b1[64] = { 0 }, b2[64] = { 0 }, b3[64] = { 0 };
// convert a to binary and store the binary string in b1[]
decimal_to_binary(b1, a);
// convert b to binary and store the binary string in b2[]
decimal_to_binary(b2, b);
// performing bitwise OR on b1[] and b2[]
// and storing the result in b3[]
for (i = 0; i < 64; ++i) {
if (b1[i] == 1 || b2[i] == 1)
b3[i] = 1;
}
// converting b3[] to decimal
c = binary_to_decimal(b3);
return c;
}
int main() {
int a, b;
printf("Enter a: ");
scanf("%d", &a);
printf("Enter b: ");
scanf("%d", &b);
printf("%d OR %d = %d", a, b, bitwiseOR(a, b));
}
Output
Enter a: 10
Enter b: 3
10 OR 3 = 11