Skip to content

Instantly share code, notes, and snippets.

@enefry
Created May 16, 2017 08:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save enefry/4ae5ac91e2437b2968c9dae32e58e204 to your computer and use it in GitHub Desktop.
Save enefry/4ae5ac91e2437b2968c9dae32e58e204 to your computer and use it in GitHub Desktop.
#ifdef _MSC_VER
#define snprintf(output,len,fmt,... ) sprintf_s(output,len,fmt,##__VA_ARGS__)
#endif // _MSC_VER
#ifdef DEBUG_DUMP_HEX_
#define DUMP_HEX_VVLOG printf("[%d]maxLen=%d offset=%d delta=%d \n",__LINE__,maxLen,offset,(maxLen-offset));
#else
#define DUMP_HEX_VVLOG
#endif
int DumpHex(char* buffer,int maxLen, const char* input, int len) {
int offset = 0;
int j, done;
int maxBit = 2;
int temp = 10;
done = 0;
for(int i=0;i<10;i++){
temp *= 10;
if(len > temp ){
maxBit ++;
}
}
if(buffer == NULL || maxLen == 0){
return (int)ceil(len*1.0/16) * (63 + maxBit * 2) ;
}
DUMP_HEX_VVLOG
for (int i = 0; i < len; i += 16) {
offset += snprintf(buffer+offset,maxLen-offset, "\n%0*d-%0*d: ", maxBit,(i),maxBit, (i + 16));
//printf("[%d]maxLen=%d offset=%d delta=%d %s\n",__LINE__,maxLen,offset,(maxLen-offset),buffer);
for (j = 0; j < 16 && (0< (maxLen-offset)); j++) {
DUMP_HEX_VVLOG
int pos = i + j;
if (pos >= len) {
done = 1;
}
if (!done) {
int c = (input[pos] & 0xff);
offset += snprintf(buffer+offset,maxLen-offset,"%02x", c);
DUMP_HEX_VVLOG
} else {
offset += snprintf(buffer+offset,maxLen-offset, "--");
DUMP_HEX_VVLOG
}
if ((j & 3) == 3) {
offset += snprintf(buffer+offset,maxLen-offset, " ");
DUMP_HEX_VVLOG
}
}
DUMP_HEX_VVLOG
offset += snprintf(buffer+offset,maxLen-offset, " |");
DUMP_HEX_VVLOG
for (j = 0; j < 16 && (0< (maxLen-offset)); j++) {
int pos = i + j;
if (pos > len) {
break;
}
int c = (input[pos] & 0xff);
if (c >= 32 && c <= 127) {
offset += snprintf(buffer+offset,maxLen-offset,"%c", c);
DUMP_HEX_VVLOG
} else {
offset += snprintf(buffer+offset,maxLen-offset, ".");
DUMP_HEX_VVLOG
}
}
for (; j < 16; j++) {
offset += snprintf(buffer+offset,maxLen-offset, " ");
DUMP_HEX_VVLOG
}
offset += snprintf(buffer+offset,maxLen-offset, "|");
DUMP_HEX_VVLOG
}
return offset;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment