Convert a Number to Hexadecimal in C++


Suppose we have an integer; we have to devise an algorithm to convert it to hexadecimal. For negative numbers we will use the two’s complement method.

So, if the input is like 254 and -12, then the output will be fe and fffffff4 respectively.

To solve this, we will follow these steps −

  • if num1 is same as 0, then −

    • return "0"

  • num := num1

  • s := blank string

  • while num is non-zero, do −

    • temp := num mod 16

    • if temp <= 9, then −

      • s := s + temp as numeric character

    • Otherwise

      • s := s + temp as alphabet

    • num := num / 16

  • reverse the array s

  • return s

Example 

Let us see the following implementation to get a better understanding −

 Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
   string toHex(int num1){
      if (num1 == 0)
         return "0";
      u_int num = num1;
      string s = "";
      while (num) {
         int temp = num % 16;
         if (temp <= 9)
            s += (48 + temp);
         else
            s += (87 + temp);
         num = num / 16;
      }
      reverse(s.begin(), s.end());
      return s;
   }
};
main(){
   Solution ob;
   cout << (ob.toHex(254)) << endl;
   cout << (ob.toHex(-12));
}

Input

254
-12

Output

fe
fffffff4

Updated on: 10-Jun-2020

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements