Write a program that will ask the user for a decimal number such as 18 and print
ID: 674929 • Letter: W
Question
Write a program that will ask the user for a decimal number such as 18 and prints the 16 bit binary equivalent of the number: 0000 0000 0001 0010
NOTE: Your output should be a binary string formatted by nibbles (spaces every four bits): 0000 0000 0010 1110 1010 0111 Normally, decimal numbers are converted to binary by repeatedly dividing the number by 2 and recording the remainder:
18 / 2 = 9, remainder: 0
9 / 2 = 4, remainder: 1
4 / 2 = 2, remainder: 0
2 / 2 = 1, remainder: 0
1 (Stop!)
we stop when the quotient become 1. Then we record the remainders (starting with the 1) in reverse order: 01001 reverses and becomes 10010. But we cannot use this method because we have no easy way of storing all these remainders. So, we have to use a different method: Ask the user for a number and store it in an int variable called “number”. Find out how many bits you want to use to represent this number.
The project indicates 16 bits. Find the value of 2 to the power of this indicated number (2 to the power of 16-1).
You may use the pow() function from the cmath library or use a loop to calculate this number (I prefer this method as it gives you a reason to practice your loops) Do not use the number for this vlaue as a constant number because this number will be changed next time the program compiles. So, we have this number and we’ll call it pow2.
Go into a loop (let’s call this the subtraction loop) and do the following:
subtract pow2 from the number you inputted.
Put a flow chart here.
if the result is non-negative,
output a 1
replace the number with the result of the subtraction
if the result is negative
output a zero at the bottom of the subtract loop, divide the pow2 by 2
continue this loop
until pow2 drops to 1
Explanation / Answer
Answer :
//Program
#include <stdio.h>
#include <cmath.h>
int main(int argc, char** argv) {
int n;
printf("Enter the decimal value: ");
scanf("%d",&n);
printf("The binary value of %d is %d", n, decimalToBinary(n));
return 0;
}
int decimalToBinary(int decimal)
{
int i, binary = 0;
for(i = 0; decimal != 0; i++) {
binary = binary + pow(10,i) *(decimal%2);
decimal = decimal/2;
}
return binary;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.