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

标签 c hex bit-manipulation

我正在阅读有关 displaying integers as hex using C 的 SO 问题(不使用 %x,通过使用自定义函数),第一个答案提到使用按位运算符来实现目标。

但我自己想不通。谁能告诉我这将如何完成?

最佳答案

我希望这能让你明白一点。

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;
}

关于C - 使用按位运算符将 int 显示为十六进制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11789458/

相关文章:

c - C 中 float 组的异或加密

c - 我的 Linux 代码中的 C 段错误

c - If 语句不断循环 - c

c - C中char*的指针问题

python-2.7 - 从十六进制值转换为二进制值

algorithm - QOI 索引哈希函数的按位加权和

c - 类型类型转换 long double 到 long long

java - 按位与非 boolean 值

c++ - 为什么在这种情况下打印错误?

c - 将 4 字节值中的特定位提取到 C 中的新变量中