Question

I'm making a program for a microcontroller (mbed LPC1768) and having a few problems to decode serial input to uint8_t.

I get a char ackBuffer[20]; filled with input from an external device. What we get is for example: F040A34B6785121\r

What I want to do is to get an uint8_t array where each number is symbolized by the hex value of 2 characters. The F is to show the message from the external device is started and the carriage return is the end of each message.

So what I want in the uint8_t array is:

0x04
0x0A
0x34
...

To make it even harder it can be the ackBuffer is a smaller size, so for example only F04004A\r (if this can be easy fixed then it's very nice, but I can work around this problem myself.

Thank you!

Was it helpful?

Solution

So I'm assuming that an ackMessage must start with 'F' and end with '\r'. And I'm even assuming that, since you work on a micro controller, anything that does more than required (eg. library functions) should be avoided. Given that you just have to iterate over the buffer:

uint8_t charToHex(unsigned char value)
{
  if (value >= '0' && value <= '9') return value - '0';
  else if (value >= 'A' && value <= 'F') return value - 'A' + 10;
  else if (value >= 'a' && value <= 'f') return value - 'a' + 10;
  assert(false);
}

#define BUFFER_SIZE (20)

int main(void)
{
  char ackBuffer[BUFFER_SIZE] = "F12345890AB\r";
  uint8_t result[(BUFFER_SIZE-2)/2]; // at most 9 bytes since it's 20 - 2 / 2

  char* ptr = ackBuffer;

  assert(*ptr == 'F');
  ++ptr;

  int count = 0;
  while(*ptr != '\r')
  {
    uint8_t value = charToHex(*ptr) << 4 | charToHex(*(ptr+1));
    result[count++] = value;
    ptr += 2;
  }

  int i;
  for (i = 0; i < count; ++i)
    printf("%x\n", result[i]);

  return 0;
}

Mind that you must have a charToHex consistent with the used encoding and probably you could need some more sanity checks around the code.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top