Home >Backend Development >C++ >How to Convert Hex Strings to Signed Integers in C ?
Consider the task of converting a hex string representation of a number to a 32-bit signed integer. For instance, the hex string "fffefffe" translates to 11111111111111101111111111111110 in binary, representing the signed integer -65538. Additionally, we need to handle both positive and negative numbers, such as "0000000A" (binary: 00000000000000000000000000001010; decimal: 10).
Leveraging the std::stringstream class, the conversion process becomes straightforward:
unsigned int x; std::stringstream ss; ss << std::hex << "fffefffe"; ss >> x;
By extracting the integer from the stream, we obtain the 32-bit signed integer representation of the hex string.
Boost's lexical_cast: Handling Errors (Discontinued)
Note: As indicated in the source answer, Boost's lexical_cast approach has been discontinued in favor of the newer C 11 functions.
Boost also provides a convenient solution that incorporates error checking:
try { unsigned int x = lexical_cast<int>("0x0badc0de"); } catch(bad_lexical_cast &) { // Handle conversion error }
Custom lexical_cast: Simple Implementation Without Error Checking
For those not utilizing Boost, a simplified version of lexical_cast can be employed without error handling:
template<typename T2, typename T1> inline T2 lexical_cast(const T1 &in) { T2 out; std::stringstream ss; ss << in; ss >> out; return out; } unsigned int x = lexical_cast<unsigned int>("0xdeadbeef");
Employing either std::stringstream or the newer C 11 utilities (such as std::stol), developers can efficiently convert hex strings to signed integers in C .
The above is the detailed content of How to Convert Hex Strings to Signed Integers in C ?. For more information, please follow other related articles on the PHP Chinese website!