sbc.c (838B)
1 /* simple base converter */ 2 3 #include <errno.h> 4 #include <stdio.h> 5 #include <stdlib.h> 6 #include <string.h> 7 8 int 9 main(int argc, char *argv[]) { 10 unsigned long n; 11 int len, base = 0, i, s; 12 13 if(argc < 2 || argc > 3) { 14 printf("Usage: %s <value> [base]\n", argv[0]); 15 return 1; 16 } 17 if(!strcmp("-v", argv[1])) { 18 printf("sbc-%s\n", VERSION); 19 return 1; 20 } 21 if(argv[2]) 22 base = atoi(argv[2]); 23 else { 24 len = strlen(argv[1]); 25 if(argv[1][len-1] == 'b' && argv[1][1] != 'x') 26 base = 2; 27 } 28 n = strtoul(argv[1], NULL, base); 29 if(errno == ERANGE || errno == EINVAL) 30 return -1; 31 printf("%lu %#04lx %lo ", n, n, n); 32 for(s = 64 - 8; s > 0 && !(n >> s); s -= 8); 33 for(i = 0; i < 8 && s >= 0; i++) { 34 printf("%d", ((n >> s) << i) & 0x80 ? 1 : 0); 35 if(i == 8 - 1) { 36 s -= 8; 37 i = -1; 38 printf(" "); 39 } 40 } 41 printf("\n"); 42 return 0; 43 }