简体   繁体   English

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

[英]C - display int as hex using bitwise operators

I was reading the SO question about displaying integers as hex using C (without using %x, by using a custom function) and the first answer mentions using bitwise operators to achieve the goal. 我正在阅读有关使用C将整数显示为十六进制的SO问题(不使用%x,而是通过使用自定义函数),第一个答案提到了使用按位运算符来实现目标。

But I can't figure it out on my own. 但是我无法自行解决。 Can anyone tell me how this would be done? 谁能告诉我该怎么做?

I hope this makes it a little clear to you. 希望这对您有所帮助。

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

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. 整数的每个4位都精确映射到一个十六进制数字,如果这四个位的值小于10,则其ASCII表示形式为'0'+值,否则为'A'+值-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. 掩码值为0x0f,并假设为32位整数,则右移从24位开始,并对于每个连续的数字递减4。

#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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM