Hex numbers in String format

Hi...i hope someone could help me on this:

I have (coming on serial port) this string: "0002003A001100100008000D00020000"...this represents hex numbers like: 0002-003A-0011-0010-0008-000D-0002-10A3 in Hex ( 2-58-17-16-8-13-2-4529 in Decimal )...so I'm reading this entire string in a char array like charBufer[50] so each place on the buffer holds one ascii of the string.....the big question...how can I convert this entire string in a way that I can store the result of each Hex number in lets say another buffer like intBuffer[8]?...thanks in advance for your help

You have to chop that string up into pieces then call atoi() strtol() each piece.

You can do this after you receive the entire string or 4 bytes at a time while you are receiving.


Rob

Here's a small example program, there's probably a shorter way but this is the first thing I thought of.

#define NUMBER_OF_VALUES 8
#define NUMBER_OF_CHARS (NUMBER_OF_VALUES * 4)
int intBuffer[NUMBER_OF_VALUES];

byte charBuffer[NUMBER_OF_CHARS +1] = {"0002003A001100100008000D00020000"};
char x[5] = {0,0,0,0,0};

void setup() {

  Serial.begin(115200);

  for (int i = 0, v = 0; i < NUMBER_OF_CHARS; ) {
    x[0] = charBuffer[i++];
    x[1] = charBuffer[i++];
    x[2] = charBuffer[i++];
    x[3] = charBuffer[i++];
    intBuffer[v++] = (byte)strtol(x,NULL,16);
  }
  for (int i = 0; i < NUMBER_OF_VALUES; i++) {
    Serial.println ( intBuffer[i], HEX);
  }
}

void loop() {

}

Rob

I'd be strongly tempted to change

    x[0] = charBuffer[i++];
    x[1] = charBuffer[i++];
    x[2] = charBuffer[i++];
    x[3] = charBuffer[i++];

to

    for (byte j = 0 ; j < 4 ; j++)
      x[j] = charBuffer[i++];
  • but then I'd also probably program the hex conversion directly rather than call atoi() :slight_smile: