Home >Backend Development >C++ >How Can I Convert a Hex String to a Signed Integer in C ?

How Can I Convert a Hex String to a Signed Integer in C ?

Susan Sarandon
Susan SarandonOriginal
2024-12-28 13:03:12520browse

How Can I Convert a Hex String to a Signed Integer in C  ?

Convert Hex String to Signed Integer in C

Many situations require converting a hexadecimal string to a signed integer in C . For instance, you may have a hex string like "fffefffe" representing a binary value of 11111111111111101111111111111110, which corresponds to the signed integer -65538.

Solution Using std::stringstream

One approach to achieve this conversion involves using std::stringstream:

unsigned int x;   
std::stringstream ss;
ss << std::hex << "fffefffe";
ss >> x;

Non-Negative Numbers

To handle non-negative numbers, you can use the following example:

#include <sstream>
#include <iostream>

int main() {
    unsigned int x;   
    std::stringstream ss;
    ss << std::hex << "0000000A";
    ss >> x;
    std::cout << static_cast<int>(x) << std::endl;
}

This will produce 10 as the result, which is correct for the hex string "0000000A".

C 11 String-to-Number Functions

In C 11, you can utilize string-to-number functions such as std::stoul:

std::string s = "0xfffefffe";
unsigned int x = std::stoul(s, nullptr, 16);

Other Approaches

Alternatively, you can leverage libraries like Boost, which offers functions like lexical_cast:

unsigned int x = boost::lexical_cast<int>("0x0badc0de");

Rolling Your Own lexical_cast

If you prefer a simpler approach without dependencies, you can use a custom implementation of lexical_cast:

template<typename T2, typename T1>
inline T2 lexical_cast(const T1 &amp;in) {
    T2 out;
    std::stringstream ss;
    ss << in;
    ss >> out;
    return out;
}

unsigned int x = lexical_cast<unsigned int>("0xdeadbeef"); 

The above is the detailed content of How Can I Convert a Hex String to a Signed Integer in C ?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn