So you basically want to convert a pair of hexadecimal digits into a numeric value. You also want to extract those values from a string.
The latter can be done using the String.charAt() method. That allows you to extract individual characters from your string.
Then you need to convert those into a number. There's a number of ways that could be done.
strtol()
The strtol() function takes three parameters - the first is a C string (NULL-terminated char array) which contains the number you want to convert, the second you can ignore, and the third is the base to convert from. So you could use something like:
char temp[3] = { char1, char2, NULL };
int val = strtol(temp, NULL, 16);
Discrete functions
It's simple enough to write a function that converts a single hex digit into a value 0-15:
unsigned char h2d(unsigned char hex)
{
if(hex > 0x39) hex -= 7; // adjust for hex letters upper or lower case
return(hex & 0xf);
}
It's then simple enough to use that to make a function that takes two hex digits and converts them into a number:
unsigned char h2d2(unsigned char h1, unsigned char h2)
{
return (h2d(h1)<<4) | h2d(h2);
}
There's as many ways of doing it as there are of skinning a cat (as the saying goes). Every way has benefits and drawbacks though. Of the two I have shown, to compare them:
- The first is "safer" as it has more error checking and can cope with other things besides hex values
- The second results in much smaller code but results with values other than hex digits are undefined.