baseconv.c (935B)
1 #include <u.h> 2 #include <libc.h> 3 4 char d[36] = "0123456789ABCDEFGHIJKLMNOPQRSTUBWXYZ"; 5 char *ibs, *obs; 6 int i, ib, ob; 7 u64int nbuf; 8 9 void 10 conv(u64int n, int base) 11 { 12 char *p, buf[258]; 13 p = buf + 257; 14 buf[257] = '\0'; 15 while (n > 0) { 16 int x = n % base; 17 n = n / base; 18 p--; 19 *p = d[x]; 20 } 21 print("%s\n", p); 22 } 23 24 void 25 usage(void) 26 { 27 fprint(2, "usage: %s -i base -o base numstr [numstr numstr ...]\n", argv0); 28 exits("usage"); 29 } 30 31 void 32 main(int argc, char **argv) 33 { 34 ARGBEGIN { 35 case 'i': 36 ibs = EARGF(usage()); 37 break; 38 case 'o': 39 obs = EARGF(usage()); 40 break; 41 default: usage(); 42 } ARGEND 43 if ((ibs == nil) || (obs == nil)) usage(); 44 ib = atoi(ibs); 45 ob = atoi(obs); 46 if ((ib < 2)||(ib > 36)) sysfatal("bad input base %d", ib); 47 if ((ob < 2)||(ob > 36)) sysfatal("bad output base %d", ob); 48 if (argc == 0) sysfatal("numstr arg missing"); 49 for (i = 0; i < argc; i++) { 50 nbuf = strtoll(argv[i], nil, ib); 51 conv(nbuf, ob); 52 } 53 }