All pastes #1225043 Raw Edit

ascii

public c v1 · immutable
#1225043 ·published 2008-10-11 00:25 UTC
rendered paste body
#include <ctype.h>#include <errno.h>#include <getopt.h>#include <stdio.h>#define ASCII 0#define DECIMAL 10#define HEX 16void usage (char* name) {    fprintf(stderr,        "usage: %s [opts] <CONVERTME>\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 <S>   print values for the ascii string S. (default)\n"        "    -d <N>   print values for the decimal number N\n"        "    -x <H>   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;			}		}	}}