/* writes a nice looking hex-dump with ascii printable chars on the right. this is for debugging purposes really. mem is the buffer to print num is the number of bytes to print out. */ void print_hex(FILE *out, unsigned char *mem, unsigned int num) { if(!out) { #if DEBUG logit(LOG_WARN,__FILE__,__LINE__,"found 'out' to be null"); #endif return; } if(!mem) { #if DEBUG logit(LOG_WARN,__FILE__,__LINE__,"found 'mem' to be null"); #endif return; } if(num < 1) return; const unsigned int bytes_per_row=16; unsigned int numlines = num / bytes_per_row; unsigned int numbytes = num % bytes_per_row; unsigned int offset = 0; unsigned int curline = 0; unsigned int curbyte = 0; unsigned char *data = mem; char *hexbuff = calloc(1,(bytes_per_row*3) + 1); if(!hexbuff) { logit(LOG_ERROR,__FILE__,__LINE__,"cannot calloc memory for hexbuff"); return; } char *hexptr=hexbuff; char *asciibuff = calloc(1,bytes_per_row+1); if(!asciibuff) { logit(LOG_ERROR,__FILE__,__LINE__,"cannot calloc memory for asciibuff"); free(hexbuff); return; } char *ascptr=asciibuff; logit(LOG_DEBUG,__FILE__,__LINE__,"print_hex printing %d lines and %d bytes",numlines,numbytes); for(curline = 0;curline < numlines;curline++) { //print a beginning of the row, which is like this: //00000000h: " fprintf(out,"%08Xh: ",offset); offset+=bytes_per_row; hexptr=hexbuff; ascptr=asciibuff; for(curbyte = 0;curbyte < bytes_per_row;curbyte++) { //first, print the hex char. sprintf(hexptr,"%02X ",(unsigned int)*data); //now print ascii variant, if it's printable if(*data >=32 && *data < 126) sprintf(ascptr,"%c ",(unsigned char)*data); else sprintf(ascptr,". "); data++; //move to hex byte in memory hexptr+=3; //three bytes for each hex char (XX ) ascptr++; //one byte for ascii chars. } //now, print this row out to the stream. fprintf(out,"%s; %s\n",hexbuff,asciibuff); } //now, we need to print any bytes which didn't quite make it //for a full line. hexptr=hexbuff; ascptr=asciibuff; fprintf(out,"%08Xh: ",offset); int leftover = (bytes_per_row - numbytes) * 3 - 1; for(curbyte = 0;curbyte < numbytes;curbyte++) { //first, print the hex char. sprintf(hexptr,"%02X ",(unsigned int)*data); //now print ascii variant, if it's printable if(*data >=32 && *data < 126) sprintf(ascptr,"%c ",(unsigned char)*data); else sprintf(ascptr,". "); data++; //move to hex byte in memory hexptr+=3; //three bytes for each hex char (XX ) ascptr++; //one byte for ascii chars. } //now, print this row out to the stream. fprintf(out,"%s ",hexbuff); for(curbyte=0;curbyte