Skip to content

Instantly share code, notes, and snippets.

@ajxchapman
Last active Jul 10, 2020
Embed
What would you like to do?
Bunch of `hexdump -C` like functions for various languages
// https://gist.github.com/richinseattle/c527a3acb6f152796a580401057c78b4
#include <stdio.h>
#include <ctype.h>
#ifndef HEXDUMP_COLS
#define HEXDUMP_COLS 16
#endif
void hexdump(void *mem, unsigned int len)
{
unsigned int i, j;
for(i = 0; i < len + ((len % HEXDUMP_COLS) ? (HEXDUMP_COLS - len % HEXDUMP_COLS) : 0); i++)
{
/* print offset */
if(i % HEXDUMP_COLS == 0)
{
printf("0x%06x: ", i);
}
/* print hex data */
if(i < len)
{
printf("%02x ", 0xFF & ((char*)mem)[i]);
}
else /* end of block, just aligning for ASCII dump */
{
printf(" ");
}
/* print ASCII dump */
if(i % HEXDUMP_COLS == (HEXDUMP_COLS - 1))
{
for(j = i - (HEXDUMP_COLS - 1); j <= i; j++)
{
if(j >= len) /* end of block, not really printing */
{
putchar(' ');
}
else if(isprint(((char*)mem)[j])) /* printable char */
{
putchar(0xFF & ((char*)mem)[j]);
}
else /* other char */
{
putchar('.');
}
}
putchar('\n');
}
}
}
package main
import (
"fmt"
"encoding/hex"
)
func main() {
fmt.Print(hex.Dump([]byte{65, 66, 67, 226, 130, 172}))
})
"""
https://gist.github.com/7h3rAm/5603718
"""
def hexdump(src, length=16, sep='.'):
FILTER = ''.join([(len(repr(chr(x))) == 3) and chr(x) or sep for x in range(256)])
lines = []
for c in range(0, len(src), length):
chars = src[c:c+length]
hexstr = ' '.join(["%02x" % ord(x) for x in chars]) if type(chars) is str else ' '.join(['{:02x}'.format(x) for x in chars])
if len(hexstr) > 24:
hexstr = "%s %s" % (hexstr[:24], hexstr[24:])
printable = ''.join(["%s" % ((ord(x) <= 127 and FILTER[ord(x)]) or sep) for x in chars]) if type(chars) is str else ''.join(['{}'.format((x <= 127 and FILTER[x]) or sep) for x in chars])
lines.append("%08x: %-*s |%s|" % (c, length*3, hexstr, printable))
return '\n'.join(lines)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment