Rolf Meyer
/
ethersniff_hex
A simple example how to receive ethernet packages and display them over stdout with an hexviewer
Diff: hexview.h
- Revision:
- 0:2f61a610595e
diff -r 000000000000 -r 2f61a610595e hexview.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/hexview.h Wed Dec 09 11:36:29 2009 +0000 @@ -0,0 +1,85 @@ +/* hexview functions + * Copyright (c) 2009 rmeyer + * Released under the MIT License: http://mbed.org/license/mit + */ + +/* Function: hexview + * Prints an array of char to stdout in hex. + * The data is grouped in two 8 byte groups per line. + * Each byte is displayed as 2 hex digits and every + * line starts with the address of the first byte. + * + * There is no text view of a line. + * + * Variables: + * buffer - The array to display. + * size - The length of buffer. + */ +inline void hexview(const char *buffer, unsigned int size) { + for(int i = 0; i < size; ++i) { + if((i%16)!=0) { + printf(" "); + } else { + printf("%04X: ", (i)); + } + printf("%02hhx", buffer[i]); + if((i%16) == 7) { + printf(" "); + } + if((i%16) == 15) { + printf("\n"); + } + } + printf("\n\n\n"); +} + +/* Function: hexview + * Prints an array of char to stdout in hex. + * The data is grouped in two 8 byte groups per line. + * Each byte is displayed as 2 hex digits and every + * line starts with the address of the first byte. + * Each line ends ub with an ASCII representation + * of the bytes. + * + * This implementation takes more stack space than the other. + * It will allocate two char arrays with a agregated size of 70 bytes. + * Therefore its faster than the fierst implementation. + * It operates directly on the char arrays and make no use of + * string manipulation functions. printf is called one time a line. + * + * Variables: + * buffer - The array to display. + * size - The length of buffer. + */ +inline void hexview2(const char *buffer, unsigned int size) { + char byte[50]; + char text[20]; + bool big = false; + int i; + for(i = 0; i < size; ++i) { + if((i&0xF) == 0x0) { + if(big) + printf("%04X: %-49s: %-20s\n", (i&~0xF), byte, text); + big = false; + byte[0] = '\0'; + text[0] = '\0'; + } else if((i&0xF) == 0x8) { + big = true; + byte[(i&0xF) * 3] = ' '; + text[(i&0xF)] = ' '; + } + unsigned char value = buffer[i]; + text[(i&0xF) + 0 + big] = (value < 0x20 || value > 0x7F)? '.': value; + text[(i&0xF) + 1 + big] = '\0'; + value = (buffer[i] &0xF0) >> 4; + byte[(i&0xF) * 3 + 0 + big] = (value < 0xA)? (value + 0x30): (value + 0x37); + value = (buffer[i] &0x0F); + byte[(i&0xF) * 3 + 1 + big] = (value < 0xA)? (value + 0x30): (value + 0x37); + byte[(i&0xF) * 3 + 2 + big] = ' '; + byte[(i&0xF) * 3 + 3 + big] = '\0'; + } + if(byte[0]) { + printf("%04X: %-49s: %-20s\n", (i&~0xF), byte, text); + } + printf("\n"); +} \ No newline at end of file