Gerstmann
Gerstmann

Reputation: 5518

Converting a string with a hexadecimal representation of a number to an actual numeric value

I have a string like this:

"00c4"

And I need to convert it to the numeric value that would be expressed by the literal:

0x00c4

How would I do it?

Upvotes: 3

Views: 4542

Answers (6)

user207421
user207421

Reputation: 310850

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.

Upvotes: 1

KitsuneYMG
KitsuneYMG

Reputation: 12901

std::string val ="00c4";
uint16_t out;
if( (std::istringstream(val)>>std::hex>>out).fail() )
{ /*error*/ }

Upvotes: 1

paxdiablo
paxdiablo

Reputation: 881113

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.

Upvotes: 3

sje397
sje397

Reputation: 41802

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;
}

Upvotes: 0

nir
nir

Reputation: 96

#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;
}

Upvotes: 2

Merlyn Morgan-Graham
Merlyn Morgan-Graham

Reputation: 59101

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;
}

Upvotes: 2

Related Questions