Write a C program to convert binary to decimal number.
/* find 2^power value */
int power(int data, int power) {
int i = 0, res = 1;
/* 2^0 is 1 */
if (power == 0)
return 1;
/* find 2^power value */
for (i = 0; i < power; i++) {
res = res * data;
}
/* return the calculated value */
return res;
}
int main() {
int data, i = 0, res = 0, rem;
/* get the input from the user */
printf("Enter your input:");
scanf("%d", &data);
/* convert binary to decimal */
while (data > 0) {
rem = data % 10;
res = res + (rem * power(2, i));
data = data / 10;
i++;
}
/* print the resultant decimal value */
printf("Result: %d\n", res);
return 0;
}
Output:
jp@jp-VirtualBox:~/$ ./a.out
Enter your input:11111111
Result: 255
Enter your input:11111111
Result: 255
No comments:
Post a Comment