# Convert a Hexadecimal String to an Integer in C++

A hexadecimal string contains only hexadecimal digits and an optional “0x” prefix. The article here discusses various ways to convert a hexadecimal string (with the “0x” prefix) to its corresponding integer value (with a note included after each method containing the changes to be made in the code in case of the hexadecimal string not containing the “0x” prefix).

## Method 1: Using a For Loop

We use a loop to manually convert each character of the hexadecimal string to its corresponding numeric value and combine them using the appropriate base (16 for hexadecimal).

Algorithm

1. In the loop, we start from the last character of the hexadecimal string and iterate backwards, skipping the “0x” prefix.
2. For each character, we first check if it is a digit using the isdigit() function.
3. If it is a digit, we convert it to its corresponding numeric value using the ‘0’ character as a reference. If it is not a digit, it must be a hexadecimal digit (A-F). In this case, we convert it to its corresponding numeric value using the ‘A’ character as a reference and adding 10 to account for the fact that hexadecimal digits A-F represent values 10-15.
4. We multiply the decimal representation of the digit by the base (which starts at 1 and is multiplied by 16 at the end of each iteration) and add it to the value to get the final result.
5. At the end of the loop, the value variable will contain the integer representation of the hexadecimal string.

Program

```#include <cctype>
#include <iostream>
#include <string>

using namespace std;

int main() {
string hex_string = "0x12345678";
int value = 0;
int base = 1;  // Initialize base to 1
for (int i = hex_string.length() - 1; i >= 2; i--) {  // Start from the last character and skip the "0x" prefix
if (isdigit(hex_string[i])) {
value += (hex_string[i] - '0') * base;
} else {
value += (toupper(hex_string[i]) - 'A' + 10) * base;
}
base *= 16;
}
cout << value << endl;
return 0;
}
```

Output

```305419896
```

Time Complexity – O(N)

• N is the length of the string.
• Since we iterate through each character of the string in the for loop to calculate the final value.

Note –

In case of hex_string not containing the prefix “0x” we iterate from (`hex_string.length() - 1)` to 0 in the for loop.

## Method 2: Using std::stoi()

One way to convert a hexadecimal string to an integer in C++ is to use the stoi function. This function is part of the header and can be used to convert a string to an integer.

To use stoi() function, you need to pass three arguments –
1. The string to be converted
2. Second is an index number, by default, it’s 0, or we can initialize it with nullptr.
3. The third is the base of the string (in this case, 16 for hexadecimal).

Program

```#include <string>
#include <iostream>

using namespace std;

int main() {
string hex_string = "0x12345678";
int value = stoi(hex_string, nullptr, 16);
cout << value << endl;
return 0;
}
```

Output

```305419896
```

Time Complexity – O(N)

Theoretically, the time complexity of the stoi() function is O(n), where n is the number of characters in the input string.

Note –

In case of hex_string not containing the prefix “0x” we will use the stoi function in the same way as above since we specify the string to be hexadecimal in the third argument of the stoi function.

## Method 3: Using sscanf

Another way to convert a hexadecimal string to an integer in C++ is to use the sscanf function. This function is part of the header and can be used to parse a string and store the result in a variable.

To use sscanf, you need to pass the following arguments –
1. The string to be converted
2. The format string specifies how the string should be parsed. To convert a hexadecimal string to an integer, you can use the ‘%x’ conversion specifier in the format string.
3. A pointer to the variable where the result will be stored.

Program

```#include <cstdio>
#include <iostream>
#include <string>

using namespace std;

int main() {
string hex_string = "0x12345678";
int value;
sscanf(hex_string.c_str(), "%x", &value);
cout << value << endl;
return 0;
}
```

Output

```305419896
```

Time Complexity – O(N)

• N is the length of the string.
• The time complexity of sscanf depends on the input string and the format string, as well as the complexity of the functions that are called as part of the parsing process. In general, sscanf has linear time complexity concerning the size of the input string, because it reads the string character by character and performs some operation at each step. However, the exact time complexity can vary depending on the specific format string and the input data.

Note –

In case of hex_string not containing the prefix “0x” we will use the sscanf function in the same way as above since we specify the string to be hexadecimal in the second argument of the sscanf function (‘%x’).

## Method 3: Using boost::lexical_cast()

boost::lexical_cast() function can only convert hexadecimal strings that start with “0x” or “0X”. If the hexadecimal string does not start with one of these prefixes, the conversion will fail and an exception will be thrown.

You will need to include the boost/lexical_cast.hpp header file in your code to use the boost::lexical_cast function. You will also need to link against the Boost library when compiling your code.

Program

```#include <boost/lexical_cast.hpp>
#include <iostream>

int main() {
std::string hex_string = "0x1234";

try {
// Convert the hex string to an integer
int value = boost::lexical_cast<int>(hex_string);
std::cout << "Value: " << value << std::endl;
// Handle the exception if the conversion fails
std::cout << "Error: " << e.what() << std::endl;
}

return 0;
}
```

Output

```Value: 4660
```

## Summary

In this article, we learned how to convert an input hexadecimal string to its equivalent integer using a for loop, stoi() function, sscanf() function and boost::lexical_cast.