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
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
char *readline(char **buf);
char *bin_to_hex(char *num);
static int strip_leading_zeroes(char **ptr) {
int result = 0;
while ((*ptr)[0] == '0' && (*ptr)[1] != '\0') {
(*ptr)++;
result++;
}
return result;
}
static inline void test_case(char *num) {
char *hex = bin_to_hex(num);
if (!hex) {
printf("Invalid input.\n");
return;
}
int leading_zeroes = strip_leading_zeroes(&hex);
printf("hex(0b%s) = 0x%s\n", num, hex);
free(hex - leading_zeroes);
}
int main(int argc, char **argv) {
char *buf = calloc(10000, 1);
while (true) {
printf("Enter a binary number to convert: ");
char *line = readline(&buf);
if (strlen(line) && strcmp(line, "exit") != 0) {
test_case(line);
}
else {
break;
}
}
}