baseConv.c (1283B)
1 #include <stdio.h> 2 #include <stdlib.h> 3 #include <string.h> 4 #include <errno.h> 5 #include <err.h> 6 #include <limits.h> 7 8 extern char* __progname; 9 10 int 11 main(int argc, char *argv[]) 12 { 13 char format[12] = "%ld\n"; 14 uint8_t base = 10; 15 long converted; 16 char *endptr; 17 18 if (argc < 2 || strlen(__progname) != 3) { 19 fprintf(stderr, "usage: d2h | d2o | d2b <base10_int>\n"); 20 fprintf(stderr, " h2d | h2o | h2b <base16_int>\n"); 21 fprintf(stderr, " o2h | o2d | o2b <base8_int>\n"); 22 fprintf(stderr, " b2h | b2o | b2d <base2_int>\n"); 23 exit(1); 24 } 25 26 if (__progname[0] == 'h') base = 16; 27 if (__progname[0] == 'o') base = 8; 28 if (__progname[0] == 'b') base = 2; 29 if (__progname[2] == 'h') 30 (void)strcpy(format, "0x%02lx\n"); 31 if (__progname[2] == 'o') 32 (void)strcpy(format, "0%02lo\n"); 33 34 converted = strtol(argv[1], &endptr, base); 35 36 if (*endptr != '\0') 37 err(1, "invalid number"); 38 if (errno == ERANGE && (converted == LONG_MAX || converted == LONG_MIN)) 39 err(1, "out of range"); 40 41 if (__progname[2] == 'b') { 42 long c, k; 43 44 for (c = (sizeof(converted) * 8) - 1; c >= 0; c--) { 45 k = converted >> c; 46 47 if (k & 1) 48 printf("1"); 49 else 50 printf("0"); 51 52 if (c % 4 == 0) 53 printf(" "); 54 } 55 printf("\n"); 56 } else { 57 printf(format, converted); 58 } 59 return 0; 60 } 61