#include <stdio.h> #include <stdint.h> #include <stdlib.h> void hexDump(void *ptr, char *buf) { static char hex[16] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; *buf++ = '0'; *buf++ = 'x'; // unsigned __int64 ip = (unsigned __int64)ptr;
uintptr_t ip = (uintptr_t) ptr;
for (int nibble = (2 * sizeof(ptr) - 1); nibble >= 0; --nibble) *buf++ = hex[(ip >> (4 * nibble)) & 0xf]; *buf = '\0'; return; } int main() { void *ptr = (void *)0x1234abcd567890ef; char buf[20]; hexDump(ptr, buf); printf("\"%s\"\n", buf); }
The above is for the conversion of x64, 64 bits because 0x1234abcd567890ef, if debug is x86, only the output value of 32 hex
The main algorithm is in
for (int nibble = (2 * sizeof(ptr) - 1); nibble >= 0; --nibble) *buf++ = hex[(ip >> (4 * nibble)) & 0xf];
Its dismantling:
int nibble = (2 * sizeof(ptr) - 1)
nibble = 15; // for x64
(ip >> (4 * nibble)) & 0xf
ip >> (4 * nibble) is directed right 15 bytes (60 bits), so that it becomes 0x0000000000000001 0x1234abcd567890ef
Then & 0xf representatives take only the last one, that is, only 1
This array can hex, the hex [1] = '1' is assigned to the array buf
Through the for loop, can all the conversion, the final output 0x1234abcd567890ef