#include <stdio.h>
#include <stdint.h>
#include <stdlib.h> void hexDump(void *ptr, char *buf)
{
static char hex[] = {
'', '', '', '', '',
'', '', '', '', '',
'A', 'B', 'C', 'D', 'E', 'F' };
*buf++ = '';
*buf++ = 'x'; // unsigned __int64 ip = (unsigned __int64)ptr;
uintptr_t ip = (uintptr_t)ptr;
for (int nibble = ( * sizeof(ptr) - ); nibble >= ; --nibble)
*buf++ = hex[(ip >> ( * nibble)) & 0xf]; *buf = '\0';
return;
} int main()
{
void *ptr = (void *)0x1234abcd567890ef;
char buf[];
hexDump(ptr, buf);
printf("\"%s\"\n", buf);
}
上面是针对x64转换的,因为0x1234abcd567890ef是64位,如果是用x86调试,只能输出32位的16进制值
主要算法是在
for (int nibble = ( * sizeof(ptr) - ); nibble >= ; --nibble)
*buf++ = hex[(ip >> ( * nibble)) & 0xf];
将其拆解:
int nibble = ( * sizeof(ptr) - )
nibble = 15; //针对x64
(ip >> ( * nibble)) & 0xf
ip >> (4 * nibble)是指向右移15个字节(60位) ,这样0x1234abcd567890ef就变成0x0000000000000001
然后再 &0xf 代表只取最后一位,即只剩 1
这样就可以根据hex数组,将hex[1] = '1'赋值给buf数组
通过for循环,可以一一转换,最后输出 0x1234abcd567890ef
补充:
#ifdef _WIN64
typedef unsigned __int64 uintptr_t;
#else
typedef unsigned int uintptr_t;