#include #include #include #include #define ASCII 0 #define DECIMAL 10 #define HEX 16 void usage (char* name) { fprintf(stderr, "usage: %s [opts] \n" "Prints the ASCII character, decimal, and hex equivalents of its\n" "arguments. Each option changes how subsequent arguments are\n" "interpreted until another option is given.\n" "Options:\n" " -a print values for the ascii string S. (default)\n" " -d print values for the decimal number N\n" " -x print values for the hexidecimal number H\n" " -h print this help and exit\n" , name); } void decode(unsigned char c) { if (isprint(c)) { printf("%1$c %1$3d 0x%1$x\n",c); } else { printf("** %1$3d 0x%1$x\n",c); } } void decode_str(char* str) { int i; for (i = 0; i < strlen(str); i++) { decode(str[i]); } } int main (int argc, char ** argv) { unsigned char c; unsigned char hexarg[3]; int i,j; int intarg = 0; int type = ASCII; char opt = 0; if (1 == argc) { usage(argv[0]); } for (i = 1; i < argc; i++) { if ('-' == argv[i][0]) { switch (argv[i][1]) { case 'a': case 'A': type = ASCII; break; case 'd': case 'D': type = DECIMAL; break; case 'x': case 'X': type = HEX; break; default: fprintf(stderr,"Unknown option %c\n",argv[i][1]); break; } } else { switch (type) { case ASCII: default: decode_str(argv[i]); break; case DECIMAL: intarg = strtol(argv[i], NULL, DECIMAL); decode((unsigned char) (intarg & 0xFF)); break; case HEX: // take arguments as two hex digits for (j = 0; j+1 < strlen(argv[i]); j+=2) { hexarg[0] = argv[i][j]; hexarg[1] = argv[i][j+1]; hexarg[2] = 0; intarg = strtol(hexarg, NULL, HEX); decode((unsigned char) (intarg & 0xFF)); } // odd number of digits, so take care of the last one if (0 != argv[i][j]) { hexarg[0] = argv[i][j]; hexarg[1] = 0; intarg = strtol(hexarg, NULL, HEX); decode((unsigned char) (intarg & 0xFF)); } break; } } } }