-
-
Notifications
You must be signed in to change notification settings - Fork 4.7k
Expand file tree
/
Copy pathbinary_to_decimal.c
More file actions
54 lines (46 loc) · 1.09 KB
/
binary_to_decimal.c
File metadata and controls
54 lines (46 loc) · 1.09 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
#include <assert.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
bool is_binary(intmax_t num);
int num_len(intmax_t num);
int main(void)
{
intmax_t remainder, number = 0, decimal_number = 0, temp = 1;
int length = num_len(INTMAX_MAX) - 1;
printf("\n Enter any binary number , max %d digits: ", length);
scanf("%jd", &number);
assert(num_len(number) <= length);
assert(is_binary(number));
// Iterate over the number until the end.
while (number > 0) {
remainder = number % 10;
number = number / 10;
decimal_number += remainder * temp;
temp = temp * 2; // used as power of 2
}
printf("%jd\n", decimal_number);
return 0;
}
bool is_binary(intmax_t num)
{
int remainder = 0;
while (num > 0) {
remainder = num % 10;
if (remainder == 0 || remainder == 1) {
num /= 10;
continue;
} else
return false;
}
return true;
}
int num_len(intmax_t num)
{
int i;
for (i = 0; num > 0; i++) {
num /= 10;
}
return i;
}