我正在阅读有关 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/