unbin.c (626B)
1 #include <stdio.h> 2 #include <stdlib.h> 3 #include <string.h> 4 #include <inttypes.h> 5 6 #define BUFFER_SIZE 256 7 8 static uintmax_t 9 bin2int(char *str) 10 { 11 uintmax_t f=1; 12 uintmax_t sum=0; 13 for (int i = strlen(str) - 1; i>=0; i--) { 14 if (str[i] == 'b') break; 15 sum = sum + f * (str[i] - '0'); 16 f *= 2; 17 } 18 return sum; 19 } 20 21 int 22 main(int argc, char **argv) 23 { 24 if (argc == 2) { 25 uintmax_t n = bin2int(argv[1]); 26 printf("%"PRIuMAX"\n", n); 27 28 return 0; 29 } 30 31 char buffer[BUFFER_SIZE]; 32 while (fgets(buffer, sizeof(buffer), stdin)) { 33 strtok(buffer, "\n"); 34 uintmax_t n = bin2int(buffer); 35 printf("%"PRIuMAX"\n", n); 36 } 37 38 return 0; 39 }