Converting issues

i have a function which is getting a char array with the contain like “AA11223344556677”.

It’s a char array with a String in it. right?!

To format this like AA and than 11 and 22 etc. each in a different variable I used this code. ( in the file below)

My buffer contains the actual line, because i have more lines like “AA11223344556677”.

So, i want to get HEX in the end to send this through CANBUS, cause i get for AA the number 187. I don’t know why.

Can someone help me on converting this to HEX in a format like followed.

format: 0xAA, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77

Thank your for your support

new 1.txt (404 Bytes)

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.

Is something like in this code you had in mind?

/*
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");
    }
  }
}