Your algorithm assumes '0' through 'F' are contiguous. Consulting an ASCII table shows this is not so, there are seven values between ASCII '9' and ASCII 'A'. Your algorithm will have to account for the gap.
Numerous threads dealing with *ascii to hex * conversion can be found with a site search.
/*
Char ASCII(Dec)
0 48
1 49
2 50
3 51
4 52
5 53
6 54
7 55
8 56
9 57
A 65
B 66
C 67
D 68
E 69
F 70
a 97
b 98
c 99
d 100
e 101
f 102
*/
uint8_t val = 0;
void byte_val(uint8_t i, uint8_t temp) {
if (i % 2 == 0) {
val |= temp << 4; //but temp in upper nibble of val
}
else {
val |= temp; //put temp in lower nibble of val
Serial.print(", 0x");
Serial.println(val, HEX);
val = 0;
}
}
void string2hex() {
uint8_t temp;
char str[17] = "Aa11223344556677"; //17 elements wide as 1 extra element required for NULL terminator ie str[16]='\0'
for (uint8_t i = 0; i < 16; ++i) {
Serial.print(str[i]);
if (str[i] > 47 && str[i] < 58) { //0-9 characters ASCII value
temp = str[i] - 48; //get the 0-9 as a number
byte_val(i, temp);
}
else if (str[i] > 64 && str[i] < 71) { //A-F characters ASCII value
temp = str[i] - 55; //get the A-F as hex number
byte_val(i, temp);
}
else if (str[i] > 96 && str[i] < 103) { //a-f characters ASCII value
temp = str[i] - 87; //get the A-F as hex number
byte_val(i, temp);
}
else {
if (i % 2 == 0) { //skip next character since current character and next character are not a valid hexadecimal repesentation of a byte
++i;
Serial.print(str[i]);
}
Serial.println(" not a valid HEX representation");
}
}
}