Skip to content

Instantly share code, notes, and snippets.

@intx82
Last active May 1, 2024 11:36
Show Gist options
  • Save intx82/99a23a350a4e95d53c0d813ec6ce855a to your computer and use it in GitHub Desktop.
Save intx82/99a23a350a4e95d53c0d813ec6ce855a to your computer and use it in GitHub Desktop.
Printing HEX in C/C++
/*
Will provide output like:
0000: ff ff ff ff ff ff 8c b8 7e 5e 99 21 08 00 45 00 ········~^·!··E·
0010: 00 e5 19 6a 00 00 80 11 99 f2 c0 a8 02 5c c0 a8 ···j·········\··
0020: 02 ff 00 8a 00 8a 00 d1 48 e4 11 02 d3 c3 c0 a8 ········H·······
0030: 02 5c 00 8a 00 bb 00 00 20 45 4a 45 4f 46 45 45 ·\······ EJEOFEE
0040: 4d 43 41 43 41 43 41 43 41 43 41 43 41 43 41 43 MCACACACACACACAC
0050: 41 43 41 43 41 43 41 43 41 00 20 46 48 45 50 46 ACACACACA· FHEPF
0060: 43 45 4c 45 48 46 43 45 50 46 46 46 41 43 41 43 CELEHFCEPFFFACAC
0070: 41 43 41 43 41 43 41 43 41 42 4e 00 ff 53 4d 42 ACACACACABN··SMB
0080: 25 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 %···············
0090: 00 00 00 00 00 00 00 00 00 00 00 00 11 00 00 21 ···············!
00a0: 00 00 00 00 00 00 00 00 00 e8 03 00 00 00 00 00 ················
00b0: 00 00 00 21 00 56 00 03 00 01 00 00 00 02 00 32 ···!·V·········2
00c0: 00 5c 4d 41 49 4c 53 4c 4f 54 5c 42 52 4f 57 53 ·\MAILSLOT\BROWS
00d0: 45 00 01 00 80 fc 0a 00 49 4e 54 4c 00 00 00 00 E·······INTL····
00e0: 00 00 00 00 00 00 00 00 0a 00 03 10 01 00 0f 01 ················
00f0: 55 aa 00 U··
*/
static void print_hex(uint8_t* buf, int sz)
{
for(int idx = 0; idx < sz; idx += 16)
{
int idx_r = idx;
printf("%04x: ", idx);
for(;idx_r < sz && idx_r < idx + 16; idx_r ++) {
printf("%02x ", buf[idx_r]);
}
if(idx_r < idx + 16) {
for (int idx_s = 0; idx_s < ((idx + 16) - idx_r); idx_s ++)
printf(" ");
}
for(idx_r = idx ;idx_r < sz && idx_r < idx + 16; idx_r ++) {
printf((buf[idx_r] >= ' ' && buf[idx_r] <='~') ? "%c" : "·", buf[idx_r]);
}
printf("\r\n");
}
printf("\r\n");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment