Write a C++ program to Set Get Clear a particular bit in a given number
Write a C++ program to set a particular bit in a given number.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
#include <iostream> using namespace std; int main() { int Number, BitPositioning; /* Get the Number input */ cout << "Enter the Number:"; cin >> Number; /* Get the bit position input */ cout << "Enter the Bit position you want to set(Between 0-31):"; cin >> BitPositioning; /*Calculating the Bit_mask*/ int Bit_mask = (1 << BitPositioning); Number = Number | Bit_mask; cout << "The Number after set the bit in the given position is:" << Number; return 0; } |
Output
Enter the Number: 4
Enter the Bit position you want to set(Between 0-31): 1
The Number after set the bit in the given position is: 6
Write a C program to get a particular bit in a given number.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
#include <iostream> using namespace std; int main() { int Number, Bit_Positioning; /* Get the Number input */ cout << "Please Enter the Number:"; cin >> Number; /* Get the bit position input */ cout << "Please Enter the Bit position you want to get(Between 0-31):"; cin >> Bit_Positioning; /* Calculating the bit Bit_Masking*/ int Bit_Masking = (1 << Bit_Positioning); /* Checking the Given Position bit is 0 or 1*/ if (Number & Bit_Masking) cout << "Given Position bit is 1.\n"; else cout << "Given Position bit is 0.\n"; return 0; } |
Write a C++ program to clear a particular bit in a given number.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
#include <iostream> using namespace std; int main() { int Number; int Bit_Positioning; /* Get the Number input */ cout << "Please Enter the Number:"; cin >> Number; /* Get the bit position input */ cout << "Please Enter the Bit position you want to Clearing(Between 0-31):"; cin >> Bit_Positioning; /* Calculating the bit Bit_Masking*/ int Bit_Masking = (1 << Bit_Positioning); /*~(Invert sign, it's convert o to 1 or 1 to 0.) */ Number = Number & (~Bit_Masking); cout << "The Number after Clearing the bit in the given position is: " << Number; return 0; } |
Output
Enter the Number: 4
Enter the Bit position you want to set(Between 0-31): 1
The Number after Clearing the bit in the given position is: 4
Write a C program to get a particular bit in a given number.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
#include <stdio.h> int main() { int Number,Bit_Positioning; /* Get the Number input */ printf("Enter the Number:"); scanf("%d", &Number); /* Get the bit position input */ printf("Enter the Bit position you want to get(Between 0-31):"); scanf("%d", &Bit_Positioning); /* Calculating the bit Bit_Masking*/ int Bit_Masking=(1<<Bit_Positioning); /* Checking the Given Position bit is 0 or 1*/ if (Number & Bit_Masking) printf("Given Position bit is 1.\n"); else printf("Given Position bit is 0.\n"); return 0; } |
Output
Enter the Number: 4
Enter the Bit position you want to set(Between 0-31): 1
Given Position, bit is 0