H
Hameed U. Khan
Hi
I've started learning C++. I want to know is there any better way of
solving the problem defined below or how can I improve the bitwise
operations. If there is any other method using bitwise operators I'll
love to know. Thanks
// Exercise 3.2
/* Object:
Creat a program that prompts the user to input an integer in decimal
form. Then, invert the last bit of its binary representation.
That is, if the last bit is 1, then change it to 0, and vice versa.
The result should then be displayer as a decimal number. How does
the adjustment affect the resulting integer value?
(Hint: use a bitwise operator.)
*/
#include <iostream>
using namespace std;
int main()
{
unsigned short num = 0;
unsigned short mask = 1;
unsigned short last_bit = 0;
cout <<"Enter number: ";
cin >> num;
last_bit = num & mask; // Extracts last bit
last_bit = ~last_bit&mask; // Inverts extracted bit
num = (num&~mask)^last_bit;
cout << "Num: "
<< num
<<endl;
return 0;
}
Hameed U. Khan
I've started learning C++. I want to know is there any better way of
solving the problem defined below or how can I improve the bitwise
operations. If there is any other method using bitwise operators I'll
love to know. Thanks
// Exercise 3.2
/* Object:
Creat a program that prompts the user to input an integer in decimal
form. Then, invert the last bit of its binary representation.
That is, if the last bit is 1, then change it to 0, and vice versa.
The result should then be displayer as a decimal number. How does
the adjustment affect the resulting integer value?
(Hint: use a bitwise operator.)
*/
#include <iostream>
using namespace std;
int main()
{
unsigned short num = 0;
unsigned short mask = 1;
unsigned short last_bit = 0;
cout <<"Enter number: ";
cin >> num;
last_bit = num & mask; // Extracts last bit
last_bit = ~last_bit&mask; // Inverts extracted bit
num = (num&~mask)^last_bit;
cout << "Num: "
<< num
<<endl;
return 0;
}
Hameed U. Khan