• 不使用C库函数(Sprintf)将void* 指针转换为十六进制字符串


    #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 = '';
        return;
    }
    
    int main()
    {
        void *ptr = (void *)0x1234abcd567890ef;    
        char buf[20];
        hexDump(ptr, buf);
        printf(""%s"
    ", buf);
    }

    上面是针对x64转换的,因为0x1234abcd567890ef是64位,如果是用x86调试,只能输出32位的16进制值

    主要算法是在

    for (int nibble = (2 * sizeof(ptr) - 1); nibble >= 0; --nibble)
            *buf++ = hex[(ip >> (4 * nibble)) & 0xf];

    将其拆解:

    int nibble = (2 * sizeof(ptr) - 1)   

    nibble = 15;   //针对x64 

    (ip >> (4 * 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;





  • 相关阅读:
    ip聚合(百度之星资格赛1003)
    encoding(hdoj1020)
    Candy Sharing Game(hdoj1034)
    you can Solve a Geometry Problem too(hdoj1086)
    Holding Bin-Laden Captive!(hdoj1085)代码并未完全看懂
    Computer Transformation(hdoj 1041)
    Digital Roots(hdoj1013)
    humble number(hd1058)
    FatMouse' Trade(hdoj1009)
    1021 Fibonacci Again (hdoj)
  • 原文地址:https://www.cnblogs.com/strive-sun/p/12073908.html
Copyright © 2020-2023  润新知