| by Arround The Web | No comments

## C++ Hex String to Int

In C++ programming language, one must deal with different data representations, i.e., binary, hexadecimal, integer, etc. Hexadecimal strings are often used to represent the binary-coded data or memory addresses which may be required to convert to integers for various operations. This article explores the process of converting the hexadecimal strings to integers in C++, covering the essential concepts, methods, and some examples to help you understand how to convert the hex strings into integers in C++ programming language.

Using a base-16 numeral system, typically referred to as hexadecimal or simply “hex”, is the standard practice in computing. In C++, hexadecimal values are commonly identified by a preceding “0x”. For instance, the hexadecimal number 0x1A equates to the decimal number 26. Hexadecimal strings consist of characters ‘0’ to ‘9’ and ‘A’ to ‘F’ (or ‘a’ to ‘f’), where ‘A’ to ‘F’ represents values 10 to 15.

Conversion between hex strings and other numerical forms like binary, integers, and decimals is feasible in C++ using the built-in functions such as stoi(), sscanf(), and stoul(), all of which facilitate the conversion from a hex string to an int. Similarly, the stringstream provides a more generalized approach. The following discussion illuminates several methods that are used to convert a hex string to its respective integer number.

## Converting a C++ Hex String to Int

C++ offers robust mechanisms to convert the hex strings to integers. The conversion process involves parsing each character within the string and calculating its equivalent decimal number. The following are some examples that show how to convert a C++ hex string to int:

Method 1: Stoi() function

The C++ standard library provides the stoi()function, adept at converting numerical strings—binary, octal, or hexadecimal—into unsigned integers within a specified base. The function is defined in the <string> header file.  It requires up to three arguments:

String Name: The numeral string intended for conversion into a decimal format.

Index Number: This optional index, by default, is 0 and can also be set to nullptr.

Base: Another optional argument which indicates the base numeral system of the provided string. Its default value is 10, denoting a decimal string input.

The stoi() function outputs an integer representation of the provided hex string. Here is the syntax of the stoi() function:

Syntax:

int stoi (string-name, index, base);

An example program in C++ that utilizes the stoi() function to convert a hexadecimal string into an integer is as follows:

#include <iostream>
#include <string>
using namespace std;
int main()
{
string s = "St";
int i = stoi(s, 0, 16);
cout << i;
return 0;
}

Let’s execute this code, examine the results, and see what we get.

The compiler throws an “invalid argument” error. Let us explain why this happened.

The stoi() function in C++ is designed to extract and convert the initial integer value from a given string argument. It processes the integers from the beginning of the string, halting upon reaching a character that is not an integer or at the string’s end.

Attempting to run the previous program results in a runtime exception because the stoi() function stops processing and exits when it encounters either a non-numerical character or a whitespace. If the string’s first character does not correspond to an integer, stoi() will terminate immediately.

Now, let us give the stoi() function with another input and see its response.

#include <iostream>
#include <string>
using namespace std;
int main()
{
string s = "1285St";
int i = stoul(s, 0, 16);
cout << "The hex string "<<s<<" is converted to integer: "<<i;
return 0;
}

The following is the output for the given input to the stoi() function:

Here, the stoi() function converts the “1285” part in the given “1285St” string and ignores the “St” part.

Method 2: Stoul() Function

The stoul() function provided by the C++ standard library within the <string> header enables the conversion from strings to integers. Similar to the stoi() function, it also requires up to three input parameters:

String Name: It represents the name of the numeral string that will be converted to an integer.

Index Pointer: A pointer to the size of the input string which is optional and defaults to 0 and can be nullptr if not used.

Base: The input of the given base number determines their interpretation and the valid characters. In this case, it is base 16 since it is a hexadecimal string.

The stoul() function outputs the integer representation of the provided hexadecimal string. Here is the syntax of the stoul() function:

Syntax:

int stoul (string-name, indexPtr, baseValue);

Here’s an example to illustrate how stoul() can be used in C++ to turn a hexadecimal string into an unsigned integer:

#include <iostream>
#include <string>
using namespace std;
int main()
{
string s = "abdgh";
int i = (s, 0, 16);
cout << "The hex string "<<s<<" is converted to integer: "<<i;
return 0;
}

The given program of the stoul() function generates the following output:

Method 3: Sscanf() Function

Now, let us dig into the sscanf() function for C++ hex to int conversion. It is included via the <cstdio> header and allows for various data conversion types, from hex strings to integers. For the sscanf() function, the following arguments need to be provided:

Input String: The string that you wish to convert to an integer.

Format String: A format string that outlines the expected format of the source string. Use the “%x” format specifier for hexadecimal to integer conversion.

Pointer: It represents a variable that stores the converted value.

The result of the sscanf() function is also a converted integer representation of the given hex string. Now, let us look at the syntax of the sscanf() function.

Syntax:

int sscanf (strng, frmt, pntr);

The following example demonstrates how the sscanf() function works to convert a C++ hex string to int. Let us see the following given example:

#include <cstdio>
#include <iostream>
#include <string>
using namespace std;
int main() {
string s = "0x1584664";
int v;
sscanf(s.c_str(), "%x", &v);
cout << "The hex string "<<s<<" is converted to integer: "<<v;
return 0;
}

As you might notice, the <cstdio> header is included in this example but not in the previous ones. This is because the sscanf() function is provided by the <cstdio> library. Another difference that you might observe here is that “0x” leads the input string. The “0x” is purposely added to the string to show that the conversion functions work the same with or without leading “0x” to the given input. The second argument of the sscanf() function is to determine the format of the string. Upon executing this program, the following output is generated:

The execution time required for the sscanf() function is influenced by the length of the input and format strings. Additionally, the time taken is affected by the complexity of the functions that are invoked during the parsing steps. Typically, sscanf() exhibits a linear time complexity (O(N)) relative to the length of the input string since it processes the string with one character at a time, performing an action with each progression. However, the precise time complexity could differ based on the specific format string and the input length.

## Conclusion

This article thoroughly examined three distinct methods for converting the hexadecimal strings to integers in C++. By delving into the details and providing practical examples, we described the use of the stoi(), stoul(), and sscanf() functions, each serving as a powerful tool in C++ for hex string to int conversion. These methods cater to different needs and scenarios: stoi() for signed integers, stoul() for unsigned long integers, and sscanf() for a more formatted approach.

Source: linuxhint.com