Convert an integer to a hex string in C++

C++Server Side ProgrammingProgramming

In this program we will see how to convert an integer to hex string. To convert an integer into hexadecimal string we can follow mathematical steps. But in this case we have solved this problem using simple trick.

In C / C++ there is a format specifier %X. It prints the value of some variable into hexadecimal form. We have used this format specifier to convert number into a string by using sprintf() function.

Input: An integer number 255
Output: FF

Algorithm

Step 1:Take a number from the user
Step 2: Make a string after converting number using %X format specifier
Step 3: Print the result.
Step 4: End

Example Code

 Live Demo

#include<iostream>
using namespace std;
main() {
   int n;
   char hex_string[20];
   cout << "Enter a number: ";
   cin >> n;
   sprintf(hex_string, "%X", n); //convert number to hex
   cout << hex_string;
}

Output

Enter a number: 250
FA
raja
Published on 28-Mar-2019 08:33:25
Advertisements