C - 使用按位运算符将int显示为十六进制

tal*_*ees 0 c hex bit-manipulation

我正在阅读使用C将整数显示为十六进制的SO问题(不使用%x,使用自定义函数),第一个答案提到使用按位运算符来实现目标.

但我无法自己解决这个问题.谁能告诉我这是怎么做到的?

Nex*_*eer 7

我希望这对你来说有点清楚.

char *intToHex(unsigned input)
{
    char *output = malloc(sizeof(unsigned) * 2 + 3);
    strcpy(output, "0x00000000");

    static char HEX_ARRAY[] = "0123456789ABCDEF";
    //Initialization of 'converted' object

    // represents the end of the string.
    int index = 9;

    while (input > 0 ) 
    {
        output[index--] = HEX_ARRAY[(input & 0xF)];
        //Prepend (HEX_ARRAY[n & 0xF]) char to converted;
        input >>= 4;            
    }

    return output;
}
Run Code Online (Sandbox Code Playgroud)