C/C++ Coding Exercise – Convert a Number to Hexadecimal?


Given a 32-bit integer (signed or unsigned), convert it to its hexadecimal in lowercase. The result should not have leading zero unless it is equal to zero. Please do not use any inbuilt converting utility. This serves as a coding exercise for beginners.

The elegant solution is to first have a lookup table defined in a const string, and concatenate the remainder in the reverse order, as shown below:

decimal_to_hexa_example C/C++ Coding Exercise - Convert a Number to Hexadecimal? beginner c / c++ leetcode online judge programming languages string

decimal_to_hexa_example

That is: 10767 in decimal equals to 2*16^3 + 10*16^2 + 0*16^1 + 15*16^0.

If the input is zero, we then need to return ‘0’ instead of the empty string.

C++ source code to convert a number to hexadecimal

Given the above explanation, here is the quick C++ function that converts a signed/unsigned 32-bit integer to its Hexadecimal string representation.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution {
public:
    string toHex(int num) {
        const string table = "0123456789abcdef"; // lookup hexadecimal
        unsigned int x = num; // make negative complement
        string r = "";
        while (x > 0) {
            int y = x % 16; // get remainder
            r = table[y] + r; // concatenate in the reverse order
            x /= 16; 
        }
        return r == "" ? "0" : r;
    }
};
class Solution {
public:
    string toHex(int num) {
        const string table = "0123456789abcdef"; // lookup hexadecimal
        unsigned int x = num; // make negative complement
        string r = "";
        while (x > 0) {
            int y = x % 16; // get remainder
            r = table[y] + r; // concatenate in the reverse order
            x /= 16; 
        }
        return r == "" ? "0" : r;
    }
};

–EOF (The Ultimate Computing & Technology Blog) —

GD Star Rating
loading...
284 words
Last Post: How to Implement and Unit Test LineSpace Algorithm in C++?
Next Post: How to Implement The Sgn Function in C++?

The Permanent URL is: C/C++ Coding Exercise – Convert a Number to Hexadecimal?

15 Comments

      • Luc Bloom
      • mathchuong89
  1. Mani
      • Mani
  2. Carlos

Leave a Reply