Open In App

Convert Hex String to Signed Integer in C++

Last Updated : 09 Feb, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

This article discusses converting a hex string to a signed integer in C++. There are 5 ways to do this in C++:

  1. Using stoi() function.
  2. Using stoul() function.
  3. Using sscanf() function.
  4. Using stringstream method.
  5. Using boost:lexical_cast.

1. Using stoi function

stoi is a function in the string header file. The function takes as an argument a string and returns the converted integer. The function syntax is as follows:

Syntax:

int stoi (char *str, size_t* idx, int base);

Here,

str: The input string that is to be converted
size: Pointer to the object whose value is set by the function
base: It specifies the radix to determine the value type of input string

Since the requirement is to convert the Hex string to an Integer, the base would be 16.

Example:

C++




// C++ program to implement
// stoi() function to convert
// hex string to signed integer
#include <iostream>
#include <string>
using namespace std;
 
// Driver code
int main()
{
  // The Hex string that is to
  // be converted
  char *str = "4AF1";
   
  // Calling the function stoi
  // Storing the return value in
  // an unsigned integer
  signed number = stoi(str, 0, 16);
   
  // Displaying the unsigned integer
  // equivalent to the hex
  cout << "hex: " << str <<
          "\tinteger: " << number;
  return 0;
}


Output

hex: 4AF1    integer: 19185

Explanation: Firstly, the relevant header files were included. Then a string is defined containing the hex 4AF1 as value. This string (character array) is passed to the stoi function along with 0 and 16 as arguments. Where 0 is the default value of the size, and 16 is for hexadecimal conversion. The return value of the function is stored in a signed integer. This Hex string, along with its signed integer equivalent, is later displayed.

2. Using stoul function

The same effect could be produced using the stoul function in the bits/stdc++.h header file. 

Syntax:

unsigned long stoul (const string&  str, size_t* idx = 0, int base = 10);

Here,

str: String object with the representation of an integral number.
idx: Pointer to an object of type size_t, whose value is set by the function to position of the next character in str after the numerical value. This parameter can also be a null pointer, in which case it is not used.
base: Numerical base (radix) determines the valid characters and their interpretation. If this is 0, the base used is determined by the format in the sequence.Notice that by default this argument is 10, not 0. 

Example:

C++




// C++ program to implement stoul()
// function to convert hex string
// to a signed integer
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
   
// Driver code
int main()
{
  // Hexadecimal string
  string str = "FF";
   
  // Converting the string to
  // unsigned integer
  unsigned num = stoul(str, 0, 16);
  
  cout << str << "is equals to " << num;
  return 0;
}


Output

FFis equals to 255

Explanation: Firstly, the string contains the value FF (255). Then this string is passed as an argument to the stoul function, along with 0 (denoting null pointer) and 16 (denoting Hexadecimal conversion). The output is stored in an unsigned integer. This variable is displayed at the end. 

3. Using sscanf function

The same effect could be produced using the sscanf function in the default C++ distribution. 

Syntax:

int sscanf(const char *str, const char *format, ...)

Here,

str: This is the C string that the function processes as its source to retrieve the data.
format: This is the C string that contains one or more of the following items: Whitespace character, Non-whitespace character and Format specifiers

Example:

C++




// C++ program to implement the
// sscanf() function to convert
// a hex string to a signed integer
#include <iostream>
using namespace std;
 
// Driver code
int main()
{
  // Hexadecimal String
  char char_string[] = "4F";
   
  // Initializing the unsigned
  // int to 0 value
  unsigned result = 0;
   
  // Calling the function and storing
  // the resultant value in the address
  // of result variable
  sscanf(char_string, "%X", &result);
   
  cout << result;
  return 0;
}


Output

79

Explanation: The string is initialized, containing the value 4F (int = 79). Another variable of unsigned int datatype is initialized with value 0. The sscanf function is called, and the string, along with hexadecimal format specifier “%X” and the integer that stores the resultant value, are passed as an argument. In the end, the value of the signed integer is displayed. 

4. Using stringstream method

The stringstream method morphs the string object with a stream to make it seem like the data is being read from a stream. The library is primarily used for parsing data stored inside strings. 

Example:

C++




#include <bits/stdc++.h>
using namespace std;
 
int main()
{
 
    unsigned x;
   
      // Hexadecimal String
    string str = "FF";
 
    // Used for segregation of characters
    istringstream iss(str);
 
    // Converting to integer and storing the result in x
    iss >> hex >> x;
 
    cout << x;
}


Output:

255

Explanation: 

Alike the previous examples, an unsigned integer variable and a string containing the hexadecimal code are stored in separate variables. Then the string is passed as an argument to the iss function. The function converts the regular string to a stream. Then the base field format is set to hex, leading to the conversion of the hexadecimal string to integer, and the result is stored in the variable x. It is done by using a hex manipulator. In the end, the unsigned value is displayed.

5. Using boost:lexical_cast

The boost:lexical_cast can convert a hex string to a signed integer. It uses stringstream behind the scenes.

Example:

C++




#include "boost/lexical_cast.hpp"
#include <bits/stdc++.h>
 
using namespace std;
using boost::lexical_cast;
 
int main() {
  
 
  string s1 = "0xFF";
   
  unsigned int x = lexical_cast<unsigned int>(s1);
  cout << x << endl;
   
}


Output:

255

Explanation: The function’s working and structure are quite similar to the ones used in the stringstream method. The only difference here is that 0x has to be prepended to the hexadecimal string to make the lexical_cast function acknowledge the presence of a hexadecimal string. After which, the string is passed as an argument to the lexical_cast function, and its result is stored. In the end, the value associated with the hex code is displayed.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads