0

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

但我自己无法弄清楚。谁能告诉我如何做到这一点?

4

2 回答 2

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;
}
于 2012-08-03T05:00:39.363 回答
3

This is not an "optimal solution". Other posters in the same thread suggested a table lookup, which is much, much better.

But, to answer your question, this is pretty much what he was suggesting:

Convert integer to hex

Each 4 bits of an integer maps to exactly one hex digit, if the value of those four bits is less than 10, then its ASCII representation is '0' + value, otherwise it is 'A' + value - 10.

You can extract each group of four digits by shifting and masking. The mask value is 0x0f, and assuming a 32bit integer, the right shift starts at 24 bits and decrements by four for each successive digit.

#include <stdio.h>

unsigned int
hex_digit (int ival, int ishift)
{
  ival = (ival >> ishift) & 0xf;
  if (ival < 10)
    ival += '0';
  else
    ival += ('a' + ival - 10);
  return ival;
}

int
main()
{
  int i = 100;
  char s[9];

  s[0] = hex_digit (i, 28);
  s[1] = hex_digit (i, 24);
  s[2] = hex_digit (i, 20);
  s[3] = hex_digit (i, 16);
  s[4] = hex_digit (i, 12);
  s[5] = hex_digit (i, 8);
  s[6] = hex_digit (i, 4);
  s[7] = hex_digit (i, 0);
  s[8] = '\0';

  printf ("hex(%d)=%s\n", i, s);
  return 0;
}

SAMPLE OUTPUT:

gcc -o tmp -g -Wall -pedantic tmp.c
./tmp
hex(100)=00000064
于 2012-08-03T05:09:18.720 回答