Ever wish you could inspect N number of bytes of memory starting from a certain address? Back in the day when I as a kid and was programming in BASIC on an Apple II, we had two BASIC instructions called PEEK and POKE, which seemed like witchcraft at the time; you used PEEK and POKE to load a magic number and stuff happened! Looking back on it now, they were just instructions to inspect and set values at addresses in memory.
Nowadays, using C, we can write out memory using printf which has a conversion character for hexadecimal, and usually people dump the more compact hex values. However, occasionally we want a bitwise dump of each byte and there’s no printf conversion for that. Therefore I find myself rewriting this over and over every time I need it, so I coded up a quick one and stuck it here for my own future reference. It’s really simple but you’re welcome to use it if you like, I hereby declare it public domain code.
void print_byte(const uint8_t x)
uint8_t mask = 0x01;
printf("%u", (x & (mask << (7-i)))!=0);
mask = 0x01;
void dump_memory(const void * mem, const size_t length)
uint8_t * byte_ptr;
byte_ptr = (uint8_t *)mem;
printf("%p:\t", (void *)byte_ptr);
char sentence = "Hello World";
dump_memory((void *)sentence, 12);
Before you go about peeking at addresses in memory, you need to make sure they’re mapped; otherwise you’d get a fault.