-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBit_basic.cpp
More file actions
51 lines (42 loc) · 786 Bytes
/
Bit_basic.cpp
File metadata and controls
51 lines (42 loc) · 786 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
#include<bits/stdc++.h>
using namespace std;
void printBinary(int num){
for(int i=5; i>=0; --i){
cout<<((num >> i) & 1);
}
cout<<endl;
}
int main()
{
// printBinary(4);
// to get idea of working of right shift..
// for(int i=5; i>=0; --i){
// cout<<4<<" "<<i<<" "<<((4>>i)&1)<<endl;
// }
// cout<<(4>>5);
int a=9;
printBinary(9);
int p=2;
//to check set bit or not set bit
if((a & (1<<5))!=0){
cout<<"set bit\n";
}
else{
cout<<"not set bit\n";
}
//set bit at 2nd position
printBinary(a | (1<<2));
//to unset bit 2nd position
printBinary(a & (~(1<<3)));
//toggle
printBinary(a ^ (1<<2));
// to count set bit
int ct=0;
for(int i=5; i>=0; --i){
if((a & (1<<i))!=0){
ct++;
}
}
cout<<ct<<endl;
return 0;
}