talloaktrees
talloaktrees

Reputation: 3718

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.

But I can't figure it out on my own. Can anyone tell me how this would be done?

Upvotes: 0

Views: 5789

Answers (2)

paulsm4
paulsm4

Reputation: 121649

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

Upvotes: 3

Next Door Engineer
Next Door Engineer

Reputation: 2886

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

Upvotes: 7

Related Questions