Convert an Integer to a Hexadecimal String in C++

A hexadecimal string contains only hexadecimal digits and an optional “0x” prefix. The article here discusses various ways to convert an integer to a hexadecimal string (with the “0x” prefix). The converted string is in lowercase and can be converted to uppercase using toupper() function in C++.

Table Of Contents

Method 1: Using a For Loop

We use a loop to repeatedly divide the input by 16 and convert the remainder to a hexadecimal digit. The hexadecimal string is constructed by appending these digits to the start of the result string.

Algorithm

  1. We first initialize an empty string hex to store the hexadecimal representation.
  2. We use a for loop that continues as long as n is greater than 0. Inside the loop, it calculates the remainder of n divided by 16 and stores it in r.
  3. Then we append the corresponding hexadecimal digit (either a number or a letter) to the start of string hex, using the expression ‘0’ + r for numbers and ‘a’ + r – 10 for letters.
  4. Finally, we divide n by 16 and the loop continues until n becomes 0.
  5. In the end, the hexadecimal string with the 0x prefix is printed

Program

#include <iostream>
#include <string>

using namespace std;

int main(){

    int n = 255;

    string hex;

    //loop runs til n is greater than 0
    while (n > 0) {
        int r = n % 16;

        //remainder converted to hexadecimal digit
        char c = (r < 10) ? ('0' + r) : ('a' + r - 10);

        //hexadecimal digit added to start of the string
        hex = c + hex;

        n /= 16;
    }

    hex = "0x" + hex;
    cout<<hex<<endl;
    return 0;
}

Output

0xff

Time Complexity – O(log(N))

  • N is an integer.
  • Since in each iteration we divide the number by 16, the time complexity will be log(N) with base 16.

Method 2: Using stringstream

This program uses the stringstream class and the hex manipulator to convert the integer to a hexadecimal string. The stringstream class is a stream that can read and write to a string, and the hex manipulator tells the stream to interpret its input as a hexadecimal number. It provides a convenient way to convert strings to and from other data types, making it a useful tool for parsing and formatting data in your C++ programs.

To use stringstream, you need to include the header file in your C++ code:

Algorithm
1. Include the sstream header file.
2. Declare a stringstream object.
3. Set the stringstream object to output in hexadecimal format using the setf function.
4. Insert the integer into the stringstream object using the operator “<<“.
5. Extract the hexadecimal string from the stringstream object using the str function.

Program

#include <iostream>
#include <sstream>

using namespace std;

int main() {

  int number = 255;

  // Declaring a stringstream object
  stringstream stream;

  // Setting the stringstream object to output in hexadecimal format
  stream.setf(ios::hex, ios::basefield);

  //Inserting the integer into the stringstream object
  stream << number;

  // Extracting the hexadecimal string from the stringstream object
  string hex_string = stream.str();

  cout << "0x" << hex_string << endl;

  return 0;
}

Output

0xff

Time Complexity – O(1)
* The overall time complexity of the program is O(1), as it consists of a series of constant-time operations.

Method 3:Using std::snprintf()

This approach uses the snprintf function, which writes a formatted string to a buffer. The %X format specifier tells snprintf to interpret the input as a hexadecimal integer.

std::snprintf is a C++ version of the C function sprintf, with additional bounds checking to prevent buffer overflows. It has the same syntax and behavior as sprintf, but is more secure in some cases. If you prefer to use the C version of the function, you can include the header and use sprintf instead.

Algorithm
1. The std::snprintf function is used to convert the integer value num to a hexadecimal string and store it in the hex buffer.
2. The format specifier %x is used to specify that the integer should be formatted as a hexadecimal value.
3. The sizeof(hex) argument specifies the size of the hex buffer, which is necessary to prevent buffer overflows.
4. The resulting hexadecimal string is then printed.

Program

#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <string>

using namespace std;

int main()
{
    int num = 255;  // The integer to be converted to a hexadecimal string
    char hex[10]; // Buffer to hold the hexadecimal string

    // Use snprintf to convert the integer to a hexadecimal string
    std::snprintf(hex, sizeof(hex), "%x", num);

    // Print the resulting hexadecimal string
    cout << "0x" << hex;

    return 0;
}

Output

0xff

Time Complexity – O(1)

  • Converting an integer to a hexadecimal string using std::snprintf involves a single function call and a fixed amount of processing, regardless of the size of the input integer. Therefore, the time complexity of this operation is constant, or O(1).

Summary

In this article, we learned how to convert an input integer to its equivalent hexadecimal string using a for loop, stringstream and snprintf function.

Leave a Comment

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.

Scroll to Top