I have a string like this:
"00c4"
And I need to convert it to a hex value like this:
0x00c4
How would I do it?
I have a string like this:
"00c4"
And I need to convert it to a hex value like this:
0x00c4
How would I do it?
The strtol
function (or strtoul
for unsigned long), from stdlib.h
in C or cstdlib
in C++, allows you to convert a string to a long in a specific base, so something like this should do:
char *s = "00c4";
char *e;
long int i = strtol (s, &e, 16);
// Check that *e == '\0' assuming your string should ONLY
// contain hex digits.
// Also check errno == 0.
// You can also just use NULL instead of &e if you're sure of the input.
You can adapt the stringify sample found on the C++ FAQ:
#include <iostream>
#include <sstream>
#include <stdexcept>
class bad_conversion : public std::runtime_error
{
public:
bad_conversion(std::string const& s)
: std::runtime_error(s)
{ }
};
template<typename T>
inline void convert_from_hex_string(std::string const& s, T& x,
bool failIfLeftoverChars = true)
{
std::istringstream i(s);
char c;
if (!(i >> std::hex >> x) || (failIfLeftoverChars && i.get(c)))
throw ::bad_conversion(s);
}
int main(int argc, char* argv[])
{
std::string blah = "00c4";
int input;
::convert_from_hex_string(blah, input);
std::cout << std::hex << input << "\n";
return 0;
}
#include <stdio.h>
int main()
{
const char *str = "0x00c4";
int i = 0;
sscanf(str, "%x", &i);
printf("%d = 0x%x\n", i, i);
return 0;
}
int val_from_hex(char *hex_string) {
char *c = hex_string;
int val = 0;
while(*c) {
val <<= 4;
if(*c >= '0' && *c <= '9')
val += *c - '0';
else if(*c >= 'a' && *c <= 'f')
val += *c - 'a' + 10;
c++;
}
return val;
}
std::string val ="00c4";
uint16_t out;
if( (std::istringstream(val)>>std::hex>>out).fail() )
{ /*error*/ }
There is no such thing as an 'actual hex value'. Once you get into the native datatypes you are in binary. Getting there from a hex string is covered above. Showing it as output in hex, ditto. But it isn't an 'actual hex value'. It's just binary.