Can someone solve how to get line: 13 has bit 0 set 13 has bit 2 set 13 has bit
ID: 3671377 • Letter: C
Question
Can someone solve how to get line: 13 has bit 0 set 13 has bit 2 set 13 has bit 3 setOr 6 has bit 1 set 6 has bit 2 set Question 2 *Write a program that prompts the user for an integer between 0 and 15 and then displays the entered value in decimal, hex, and binary *It should then display which bits in the binary representation of the number are set, where bit 0 is the least significant bit. Please enter an integer between 0 and 15: -1 Invalid entry Please enter an integer between 0 and 15: 16 Invalid entry Please enter an integer between 0 and 15: 13 13 (in decimal) 0xd (in hexadecimal)-1101 (in binary) 13 has bit 0 set 13 has bit 2 set 13 has bit 3 set Please enter an integer between 0 and 15: 6 6 (in decimal) 0x6 (in hexadecimal)-0110 (in binary) 6 has bit 1 set 6 has bit 2 set Please enter an integer between 0 and 15: 15 | 15 (in decimal) -0xf (in hexadecimal) -1111 {in binary} 15 has bit 0 set 15 has bit 1 set 15 has bit 2 set 15 has bit 3 set ECE 114 Lab 8-Bit Operators and Random Numbers
Explanation / Answer
#include <iostream>
#include <string>
using namespace std;
int main()
{
string hex = "0x",bin = "", rev_bin = "";
int n,m;
while(true)
{
cout<<"Enter a number between 0 and 15 (inclusive):: ";
cin>>n;
if(n<0||n>15)
{
cout<<"Invalid entry ";
continue;
}
else
break;
}
if(n>=10)
hex += 'a'+(n-10);
else
hex += '0' + n;
m = n;
while(m!=0)
{
if(m%2==1)
bin += "1";
else
bin += "0";
m /= 2;
}
for(m=bin.size()-1;m>=0;m--)
rev_bin += bin[m]; //reverse binary string
cout<<n<<" (in decimal) = "<<hex<<" (in hexadecimal) and "<<rev_bin<<" (in binary) ";
for(m=0;m<bin.size();m++)
if(bin[m]=='1')
cout<<n<<" has bit "<<m<<" set ";
}