In c++ Write a program that reads in a decimal number n and a position index. Convert the decimal number into binary format and print
In c++
Write a program that reads in a decimal number "n" and a position "index". Convert the decimal number into binary format and print out the number in binary format.
Next, implement the following functions to get, set, and clear the bit at the position "index" of the number.
Finally, using your functions, print the following three things: 1) the original bit at position "index" of "n"; 2) the number "n" with the bit at "index" set; 3) the number "n" with the bit at "index" cleared.
/*
Retrieve a bit from a number "n" in binary format at position "index"
Input: number n, position index with 0 being the right most (least significant) bit
Output: bit at position "index"
Example: Input: n=1010, index=1, output=1
*/
int getBit(int n, int index)
/*
Set a bit at position "index"
Input: number n, position index with 0 being the right most (least significant) bit
Output: the binary number after the bit is set at position "index"
Example: Input: n=1010, index=0, output=1011
*/
int setBit(int n, int index)
/*
Clear a bit at position "index"
Input: number n, position index with 0 being the right most (least significant) bit
Output: the binary number after the bit is cleared at position "index"
Example: Input: n=1010, index=1, output=1000
*/
int clearBit(int n, int index)
Note: To display a decimal number in 8-bit binary format, use std::bitset<8>(n).
Example: std::bitset<8>(4) if n = 4 will output 00000100.
Step by Step Solution
There are 3 Steps involved in it
Step: 1
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started