Skip to content

Commit 2909612

Browse files
committed
Added code for bitwise operations
1 parent 860188c commit 2909612

File tree

5 files changed

+28
-0
lines changed

5 files changed

+28
-0
lines changed

.DS_Store

8 KB
Binary file not shown.

Competitive Coding/.DS_Store

8 KB
Binary file not shown.
Binary file not shown.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
#include <bits/stdc++.h>
2+
using namespace std;
3+
4+
int main()
5+
{
6+
int n,i;
7+
printf("Enter a number:\n");
8+
scanf("%d",&n);
9+
printf("Enter bit to be checked:\n");
10+
scanf("%d",&i);
11+
if( n & (1 << i) )
12+
printf("The %dth bit is set in %d",i,n);
13+
else
14+
printf("The %dth bit is not set in %d",i,n);
15+
return 0;
16+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
#Check whether the ith bit is set in a number using Bitwise Operations
2+
3+
Let’s say we have a number N, and to check whether it’s ith bit is set or not, we can AND it with the number 2^i . The binary form of 2^i contains only ith bit as set (or 1), else every bit is 0 there. When we will AND it with N, and if the ith bit of N is set, then it will return a non zero number (2^i to be specific), else 0 will be returned.
4+
5+
Using Left shift operator, we can write 2^i as 1 << i .
6+
7+
Example:
8+
Let’s say N = 20 = {10100}2. Now let’s check if it’s 2nd bit is set or not(starting from 0). For that, we have to AND it with 2^2 = 1<<2 = {100}base 2 .
9+
{10100} & {100} = {100} = 2^2 = 4(non-zero number), which means it’s 2nd bit is set.
10+
11+
12+

0 commit comments

Comments
 (0)