In: Computer Science
Q6. Perform the following operations using bit masking.
(a)
Set the bit 3 of a byte data
(b)
Clear the bit 5 of a byte data
(c)
Toggle the bit 7 of a byte data
(d)
Check the bit 0 of a byte data
#include <iostream>
using namespace std;
int main()
{ //int is of 32 bit but we only see on its last 8 bit
int num,mask,pos,ans; //num for example take 86 in binary
01010110
num = 86; //mask is for masking and pos for position where we have
to perform
cout<<"Number is "<<num<<endl;
/* Part 1*/
cout<<"------ part 1-------"<<endl;
pos = 3; // Q1 set bit 3 of byte data
mask = (1<<pos); // left shift 1 three times which make
00001000 = 8 in decimal
ans = num|mask; // 01010110 num
cout<<"ans :"<<ans<<endl; // 00001000 mask bit
wise or
// 01011110 ans = 94
/* part 2 */
cout<<"------ part 2-------"<<endl;
pos = 5; // Q2 clear bit 5 of byte data
mask = (1<<(pos-1)); // mask = 00010000 = 16 in decimal
ans = num &(~mask); // ~mask = 11101111 bit wise not
cout<<"ans :"<<ans<<endl; // 01010110 num
// 11101111 ~mask bit wise andoperation
// 01000110 ans = 70
/* part 3 */
cout<<"------ part 3-------"<<endl;
pos = 7; // Q3 toggle bit 7 of byte data
mask = (1<<pos); // mask = 10000000 = 64 in decimal
ans = num^mask; // 01010110 num
// 10000000 mask bit wise xor operation
cout<<"ans :"<<ans<<endl; // 11010110 ans =
214
/* part 4 */
cout<<"------ part 4-------"<<endl;
pos = 0; // Q4 check bit 0 of byte data
mask = (1<<pos); // mask = 00000001
ans = num&mask; // 01010110 num
if(ans == 1) // 00000001 mask bit wise and operation
cout<<"SET BIT AT POSITION"; // 00000000 ans = 0 if last bit
is not set then our ans = 0
else // and if it is set then ans =1
cout<<"NOT SET";
cout<<endl;
return 0;
}
/* In above code you can generalize it by taking num and pos as a
input so it gives answer all all other queries*/