/* Sample HW2 - code to display continuous regions of memory one byte at a time, in binary, hex or decimal */ #include /* tobin converts an 8 bit value (char) to an ASCII string. The string will contain exactly 8 characters, each one is either '1' or '0'. The string returned is null terminated. Note that the return value is the address of a local variable! This is only possibly because the local variable (s) is declared static. */ char *tobin(char x) { static char s[100]; int i; for (i=0;i<8;i++) { if (x & (0x01 <<(7-i))) { s[i]='1'; } else { s[i]='0'; } } s[8]=0; /* terminate the string */ return(s); } /* showbyte will display a single byte and it's address. The format used is determined by the char fmt, which can be 'd' (for decimal), 'x' (for hex) or 'b' (for binary). decimal values are displayed as unsigned, so the value can be between 0 and 255. */ void showbyte(char *addr, char fmt) { char x = *addr; switch(fmt) { case 'd' : printf("%08x: %d",addr,(unsigned char)x); break; case 'x' : printf("%08x: %02x",addr,(unsigned char)x); break; case 'b' : printf("%08x: %s",addr,tobin(x)); break; default: printf("Unknown format: %c\n",fmt); break; } } /* converts from an ASCII encoded hex string to a C int sscanf does all the work. note this doesn't check for errors in the conversion. if s doesn't really hold an ASCII encoded hex string the return value is basically undetermined (could be anything!). */ int fromhex(char *s) { int x; sscanf(s,"%x",&x); return(x); } /* main program expects 2 command line parameters, the address to start at (as hex) and the format specified */ int main(int argc, char **argv) { int addr; char format; int done=0; char s[1000]; /* get the starting address from the command line */ addr = fromhex(argv[1]); /* get the format specifier (first char of the 2nd arg) */ format = argv[2][0]; /* do until user presses 'q' */ while (! done) { showbyte(addr,format); addr++; fgets(s,1000,stdin); /* read an entire line */ if (s[0]=='q') done=1; /* set done if we find 'q' */ } return(0); }