STRING To HEX Converter

PaulS:

How to convert a text string "003C" to Hex value 0x003C ?

Use strtoul().

Or even better -- don't use strtoul(). In fact, don't use the C++ string library at all, if you can possibly avoid it.

Assuming null delimited C-style strings (really character arrays declared like char s[] = "this is an C-style string"; ), you can write a simple conversion fn in a few lines like this:

int x2i(char *s) 
{
  int x = 0;
  for(;;) {
    char c = *s;
    if (c >= '0' && c <= '9') {
      x *= 16;
      x += c - '0'; 
    }
    else if (c >= 'A' && c <= 'F') {
      x *= 16;
      x += (c - 'A') + 10; 
    }
    else break;
    s++;
  }
  return x;
}

Pass a string like

int v = x2i("003C");

or

int v = x2i(s);

and you will get a numeric conversion from a string of hexadecimal digits. Note this won't work for lower case letters (although easy to add -- I will leave as an exercise). It will stop converting on the first character it finds that is not 0-9 or A-F (hopefully that would be the null delimiter!), but be aware it would also return x2i("Can I have a slice of toast?") as 12 (i.e. 0x0C), for example.

(BTW, once an integer type variable holds a value, it makes no sense to describe it as decimal or hex or octal -- those are string representations for human readability. The integer v will hold exactly the same value for int v = 12; and v = 0x0C; for example. So really, the title of the post should really be something like "hex string to int converter".)

Hope that helps.