/* abc - Arbitrary Base Converter, ver. 1.03 * * Copyleft (l) Stanislav Sokolov, February 2000 * Send comments and bugs to stanisls@ifi.uio.no * The latest source can be found at: * http://members.tripod.com/~stanislavs/prog/source.htm * * This program is subject to GNU General Public License * Version 2 of June 1991 or any later version. */ #include #include #include #include int digval(char c){ if(c < 'A') return c - '0'; return (c & 0xDF) - 'A' + 10; } void help(void){ printf("\nabc - Arbitrary Base Converter, ver 1.03\n" "Copyleft (l) Stanislav Sokolov (stanisls at ifi dot uio dot no), Feb. 2000\n\n" "The program accepts numbers in decimal, hexadecimal, octal or binary forms\n" "and displays them in all these froms. The numbers can be entered using the\n" "following formats:\n\n" "1234\t-\tdecimal\n" "0x1234\t-\thexadecimal\n" "01234\t-\toctal (note the leading zero)\n" "0b0101\t-\tbinary (leading bits filled with zeros)\n" "1b0101\t-\tbinary (leading bits filled with ones)\n" "'x'\t-\textended ASCII value of 'x', where x is any char\n\n" "help\t-\tshow this help\n" "quit\t-\tstops the program\n\n"); } int main(void){ unsigned long num, x; //The Number and its helper int i, size = sizeof(num) * 8; unsigned char snum[36]; help(); do{ //Get a number printf("abc: "); fflush(stdin); if(fgets(snum, 36, stdin) == NULL) break; if(snum[strlen(snum) - 1] == '\n') snum[strlen(snum) - 1] = '\0'; //Check which base the numbers has num = 0; if(snum[1] == 'b'){ //binary for(i = size - 1; i >= 0; i--){ //Ensure correct expansion if(i < strlen(snum) - 2) x = snum[strlen(snum) - i - 1]; else x = snum[0]; x -= '0'; if(x > 1){ printf("Illigal number\n\n"); num = 0; break; } num |= x << i; } }else if(snum[1] == 'x'){ //hex for(i = 2; i < strlen(snum); i++){ x = digval(snum[i]); if(x > 15){ printf("Illigal number\n\n"); num = 0; break; } num |= x << (strlen(snum) - 1 - i) * 4; } }else if(snum[0] == '0'){ //octal for(i = 1; i < strlen(snum); i++){ x = snum[i] - '0'; if(x > 7){ printf("Illigal number\n\n"); num = 0; break; } num |= x << (strlen(snum) - 1 - i) * 3; } }else if(snum[0] == '\''){ //ASCII num = snum[1]; }else if(snum[0] == 'h'){ //Help help(); }else if(snum[0] == 'q'){ //Quit printf("\n"); return 0; }else if (snum[0] == '-' || isdigit(snum[0])){ //decimal i = 0; if(snum[0] == '-') i++; for(; i < strlen(snum); i++) num = num * 10 + (snum[i] - '0'); if(snum[0] == '-') num *= -1; } //Make numbers if(num != 0){ //print it in a decimal, hex and octal forms... printf(" Signed: %11ld; Octal: 0%.11lo; Hex: 0x%.8lX;\n" " Unsigned: %10lu; Binary: ", num, num, num, num); //print the binary number in 4-bit chunks for(i = size - 1; i >= 0; i--){ printf("%ld", (num >> i) & 1); if(!(i % 4)) printf(" "); } printf("\n"); } }while(1); return 0; }