Converting an Integer to a Hexadecimal String

This post presents a nice and efficient algorithm to convert an integer into a hexadecimal string using the properties of binary numbers. Source code in the C language is provided along with examples.

Hexadecimal conversion

Just quickly sharing an algorithm to convert an unsigned decimal integer to a string of hexadecimals. Normally to do this as a human, the first way that everyone is taught is to progressively divide by the base (16) and keep the remainders. While this is not wrong, there are of course much faster ways and I would like to share one in this post.

There is a reason that hexadecimals are universally utilized in computing in order to represent numbers. They are very well fit to do so. Let’s take for example the number 2579541374shown below and see what I mean.

Binary Representation of a Decimal
Binary Representation of a Decimal

Hexadecimals are numbers with 16 as a base, which is a power of 2. 2 in the power of 4 to be more specific. Let’s see what happens if we group that big binary number into groups of 4 bits.

Binary Number divided into groups of 4 bits
Binary Number divided into groups of 4 bits

It looks much more presentable now, right? But what have we achieved? Well by dividing the big integer into groups of 4 bits we have almost already converted it into a hexadecimal. Why so? Well a string of 4 bits can represent numbers 0 to 15. And it’s no coincidence that 0 to 15 are exactly the digits of the hexadecimal numbers.

Hex Conversion Table
Hex Conversion Table

So the “algorithm” consists of nothing more other than simply taking each 4 of the bits of the integer and figuring out the hexadecimal digit they correspond to. For 2579541374the solution is shown below.

Hexadecimal conversion
Hexadecimal conversion

Putting all of the above into C code is very easy. By sacrificing 16 bytes of memory to keep an array of the hexadecimal digits we can convert all possible integers.

static char hex [] = { '0', '1', '2', '3', '4', '5', '6', '7',
                        '8', '9' ,'A', 'B', 'C', 'D', 'E', 'F' };
 
//The function that performs the conversion. Accepts a buffer with "enough space" TM 
//and populates it with a string of hexadecimal digits.Returns the length in digits
int uintToHexStr(unsigned int num,char* buff)
{
    int len=0,k=0;
    do//for every 4 bits
    {
        //get the equivalent hex digit
        buff[len] = hex[num&0xF];
        len++;
        num>>=4;
    }while(num!=0);
    //since we get the digits in the wrong order reverse the digits in the buffer
    for(;k<len/2;k++)
    {//xor swapping
        buff[k]^=buff[len-k-1];
        buff[len-k-1]^=buff[k];
        buff[k]^=buff[len-k-1];
    }
    //null terminate the buffer and return the length in digits
    buff[len]='\0';
    return len;
}

The function should be simple enough to understand without any explanation. It takes every 4 bits of the integer and matches the corresponding hex digit which it saves inside the buffer. Of course since this produces the reverse of the hexadecimal we want (since we read the number from the LSB) we need to reverse it in the end. That is achieved by simple XOR swapping. To use the function you would do something like below

#include  
 
int main()
{
   char buff[16];//enough for 64 bits integer
   int length;   
   //convert
   length = uintToHexStr(3735928559,buff);
   //and print the results
   printf("0x%s with length:%d",buff,length);
   return 0;
}

The above would output 0xDEADBEEF(^_^) with length:8. So that’s all, hope you liked the explanation of the way to convert an integer to a hexadecimal string and if you have any questions don’t hesitate to leave a comment below.

In addition if the post caught your interest and you love C programming in general why not check my work in the Refu Library? It currently needs more contributors and people who are able and willing to provide feedback! You could be one of them 🙂

2 thoughts on “Converting an Integer to a Hexadecimal String”

  1. Small note, your code has html chars for the greater then and ampersand.

    And the line: num>>=4;
    should be: num = num >> 4;

  2. Hey Michael,
    Thanks for the comment. This is rather an old post and I moved it from another host so the html characters appeared out of the blue. Fixed them.

    Why should num >>= 4; be num = num >> 4? Are they not equivalent?

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.