Write a program that solves the problem described in Chapter 4 problem number 4.
ID: 3665180 • Letter: W
Question
Write a program that solves the problem described in Chapter 4 problem number 4.25 from the text. A screen
capture of the problem statement is given below:
Hint:
Binary Numbers – Base 2
- 2 distinct digits (0, 1)
- A binary number represents a power series of 2.
Example:
(10101)2 = 24 × 1 + 23 × 0 + 22 × 1 + 21 × 0 + 20 × 1 = (21)10
Method for Converting from Decimal to Binary
1) Repeatedly subtract the largest power of 2 that produces a nonnegative result.
2) Construct the binary number by placing ones in the positions corresponding to the powers of two subtracted in
step 1 and zeroes in all the other positions.
Example:
Convert the decimal value 171 to binary.
171 – 27 = 43
43 – 25 = 11
11 – 23 = 3
3 – 21 = 1
1 – 20 = 0
(171)10 = (10101011)2
Explanation / Answer
Code:
#include <iostream>
using namespace std;
int main()
{
int a[32]={0};
int i,n,temp;
string res="";
cout<<"enter the decimal number which should be converted to binary "<<endl;
cin>>n;
temp=n;
for(i=30;i>=0;i--)
{
if(n>=(1<<i))
{
cout<<n<<" - 2^"<<i<<" = "<<(n-(1<<i))<<endl;
n=n-(1<<i);
a[i]=1;
}
}
for(i=30;i>=0;i--)//find the highest power of 2 whose value is 1 in binary representation
if(a[i]==1)
break;
for(;i>=0;i--)
{
if(a[i]==1)
res+="1";//place 1 if the 2^i is 1 in binary representation
else
res+="0";//place 0 if the 2^i is 0 in binary representation
}
cout<<temp<<"_10 = "<<res<<"_2"<<endl;
return 0;
}
Output:
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.