Create a program to ask the user for an integer number, positive only. If the number is between 0 and 255, printout the number in binary format to the screen. This will involve checking the bits, one by one, starting from the most significant place: 128.
Use c++
1. Modify the program to find the binary number, using a FOR loop, instead of the manual checking of each bit separately
2. What are the bitwise XOR and INVERSION operators? Find them and create a program that uses them. For the XOR, ask the user for a number, and XOR it with a hardcoded binary constant like 0b01010101. For the inversion, ask the user for a number, and print the result of its bitwise inversion, in both decimal and binary
Ans 1. Using a For Loop
#include <iostream>
using namespace std;
void DecimalToBinary(int n)
{
int binaryNumber[100], num=n;
int i = 0;
while (n > 0) {
binaryNumber[i] = n % 2;
n = n / 2;
i++;
}
cout<<"Binary form of "<<num<<" is ";
for (int j = i - 1; j >= 0; j--)
cout << binaryNumber[j];
}
int main() {
int a;
cout<<"Enter the Number bw 0 to 255 : ";
cin>>a;
if(a >= 0 && a <= 255)
DecimalToBinary(a);
return 0;
}
Ans 2.
Bitwise XOR (^): Before Bitwise XOR we need to know about XOR operation. Here is the truth table of XOR operation
a | b | a ^ b |
0 | 0 | 0 |
0 | 1 | 1 |
1 | 0 | 1 |
1 | 1 | 0 |
In Bitwise XOR we perform XOR operation of every bit.
ex. 1 0 0 1 0 0
1 1 1 0 1 0
0 1 1 1 1 0
Bitwise Inversion(~): In Bitwise Inversion we invert every bit of the given binary number.
Ex a = 5 = 101
After Bitwise Inversion ~a will be -6.
~(0 0 0 0 0 1 0 1) = 1 1 1 1 1 0 1 0 = - 6
Bitwise XOR Code:
#include <iostream>
using namespace std;
int main()
{
int num1,num2;
cout<<"Enter the First Number = ";
cin>>num1;
cout<<"Enter the Second Number = ";
cin>>num2;
cout<<"Bitwise XOR of these Numbers( num1 ^ num2 ) " <<
(num1 ^ num2)<<endl;
return 0;
}
Bitwise Inversion Code
#include <iostream>
using namespace std;
void DecimalToBinary(int n)
{
int binaryNumber[100], num=n;
int i = 0;
while (n > 0) {
binaryNumber[i] = n % 2;
n = n / 2;
i++;
}
cout<<"Binary form of Inversion Number "<<num<<"
is ";
for (int j = i - 1; j >= 0; j--)
cout << binaryNumber[j];
}
int main()
{
int num1;
cout<<"Enter the Number = ";
cin>>num1;
cout<<"Bitwise Inversion of the Number in Decimal = "
<< ~(num1)<<endl;
DecimalToBinary(~num1);
return 0;
}
e3fwsdfrewq
Get Answers For Free
Most questions answered within 1 hours.