In: Computer Science
For this week’s lab assignment, you will write a program called lab9.c. You will write a program so that it contains two functions, one for each conversion. The program will work the same way and will produce the same exact output. The two prototypes should be the following: int btod(int size, char inputBin[size]); int dtob(int inputDec); The algorithm for the main() function should be the following: 1. Declare needed variables
2. Prompt user to enter a binary number
3. Use scanf() to get that value
4. If getting it as a string, use strlen() to find the length of the string
5. Call btod() function sending to it the size and the value that was entered by the user and save the return value so the result can be printed out
6. Prompt user to enter a decimal number
7. Use scanf() to get that value
8. Call dtob() function saving the return value in a variable so the result can be printed out
Don’t forget to break the program into smaller steps and compile and run AFTER EACH STEP.
Hi
I have written the program for binary to decimal and decimal to binary and its working fine, please compiler and test at your end, if you have any questions please let me know.
// readFileCalavg.cpp : Defines the entry point for the console
application.
//
#include "stdafx.h"
#include <string.h>
#include <stdlib.h>
#include <iostream>
int btod(int size, char inputBin[64]) {
int decimalOutput = 0, i = 0, powerMul;
powerMul = size - 1;
while (i<size) {
decimalOutput = decimalOutput +
(pow(2, powerMul) * (inputBin[i] - 48));
i++;
powerMul--;
}
return decimalOutput;
}
long dtob(int inputDec) {
long binarynum = 0, rem, place = 1;
while (inputDec > 0)
{
rem = inputDec % 2;
binarynum += rem * place;
place *= 10;
inputDec /= 2;
}
return binarynum;
}
int main()
{
char binaryInput[64];
int decimalInput = 0;
printf("Please enter the binary number\n");
scanf("%s", binaryInput);
printf( " The decimal number is : %d
\n",btod(strlen(binaryInput),binaryInput));
//-----------------------------
printf("Please enter the decimal number\n");
scanf("%d", &decimalInput);
printf(" The binary number is : %ld \n",
dtob(decimalInput));
getchar();
getchar();
return 0;
}
Thanks