Bit manipulation has four operations:
- set the bit
- clear the bit
- check the bit
- toggle the bit
Bit manipulation in C++
First we need to know the basic.
AND (&) Operation:
Binary result always comes in 0 or 1, It’s multiplication so 1&1 = 1 and other will come as zero.
Input 1 | Input 2 | Result |
0 | 0 | 0 |
0 | 1 | 0 |
1 | 0 | 0 |
1 | 1 | 1 |
OR (|) Operation:
Binary result always comes in 0 or 1, It’s addition so 0|0 = 0 and other will come as one.
Input 1 | Input 2 | Result |
0 | 0 | 0 |
0 | 1 | 1 |
1 | 0 | 1 |
1 | 1 | 1 |
XOR (^) Operation:
Binary result always comes in 0 or 1. (If both input are same then its zero)
Input 1 | Input 2 | Result |
0 | 0 | 0 |
0 | 1 | 1 |
1 | 0 | 1 |
1 | 1 | 0 |
Operation:
- set the bit: num = num | (1 << pos); //OR operator (0 | 1 = 1 , 1| 1 = 1)
- clear the bit: num = num & ~(1<< pos); // AND operator ( 0 & 0 = 0, 1 & 0 = 0)
- check the bit: bool ch = num & (1<<pos)?true:false; //OR operator (0 & 1 =0, 1& 1 = 1)
- toggle the bit: num = num^(1<<pos);
Source code with example:
/* Program: Bit Manipulation Author: Alpha Master Date: 03 Nov 2021 */ //Header File #include<iostream> int main() { std::cout<<"Bit OPeration"<<std::endl; //its interger number and 4 byte, its each bit we can set //so we can use single integer to store 32 flags. int num = 0; int pos = 0; //setting //set the 5th bit //pos is starting from zero position pos = 4; num = num | (1 << pos); //expected answer is 16 (10000) std::cout<<"value:"<<num<<std::endl; //set the 4th bit, expected answer is 11000 = 24 pos = 3; num = num | (1 << pos); std::cout<<"value:"<<num<<std::endl; //set the 1st pos, expected answer is 11001 = 25 pos = 0; num = num | (1 << pos); std::cout<<"value:"<<num<<std::endl; //clear pos = 0; num = num & ~(1<< pos); //expecting 24 std::cout<<"value:"<<num<<std::endl; //check 5th bit pos = 4; bool ch = num & (1<<pos)?true:false; //expecting true std::cout<<"Status:"<<ch<<std::endl; pos = 2; ch = num & (1<<pos)?true:false; //expecting false std::cout<<"Status:"<<ch<<std::endl; //toggle num = num^(1<<pos); //expecting true ch = num & (1<<pos)?true:false; std::cout<<"Status:"<<ch<<std::endl; //toggle again num = num^(1<<pos); //expecting false ch = num & (1<<pos)?true:false; std::cout<<"Status:"<<ch<<std::endl; return 0; }
Output:
Bit OPeration value:16 value:24 value:25 value:24 Status:1 Status:0 Status:1 Status:0