Write the function int bin2dec(int n, int bin []), which given a binary array, r
ID: 3807985 • Letter: W
Question
Write the function int bin2dec(int n, int bin []), which given a binary array, returns the equivalent decimal value. (a) Write a program (you can put everything in main) which given a decimal number, creates the table which shows the steps for how it is converted to decimal. (b) Turn your program into a function called int dec2bin(int dec, int bin[]) which given a decimal number, sets up the corresponding binary array. Also, it returns (as an int) the number of bits contained in bin []. Write the functions: (a) void bin2hex (int n, int bin[], char hex[]) (b) void hex2bin (int n, int bin[], char hex[])Explanation / Answer
24.
int bin2dec(int n, int bin[])
{
int rem;
long dec = 0, i=0;
while(n != 0) {
rem = n%10;
n = n/10;
dec = dec + (rem*pow(2,i));
++i;
}
return dec;
}
25.a)
#include <stdio.h>
#include <math.h>
int main()
{
int n;
//Take input from user
printf("Enter a decimal number: ");
scanf("%d", &n);
//fuction which convert Decimal number into Binary
long long convertDec2Bin(int n)
{
long long binNum = 0;
int rem, i = 1, step = 1;
//loop until n equals to zero
while (n!=0)
{
rem = n%2;
//Print the steps of converstion
printf("Step %d: %d/2, Remainder = %d, Quotient = %d ", step++, n, remainder, n/2);
n /= 2;
binNum += rem*i;
i *= 10;
}
return binNum;
}
//Print the final output
printf("%d in decimal = %lld in binary", n, convertDec2Bin(n));
return 0;
}
Sample output :
Enter a decimal number: 27
Step 1: 27/2, Remainder = 1, Quotient = 13
Step 2: 13/2, Remainder = 1, Quotient = 6
Step 3: 6/2, Remainder = 0, Quotient = 3
Step 4: 3/2, Remainder = 1, Quotient = 1
Step 5: 1/2, Remainder = 1, Quotient = 0
27 in decimal = 11011 in binary
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.