-1
char str[] = "05AD2101";

I have a function sendChar and I want to send this str chars in a pair of two as hex values as follows:

sendChar(0x05);

sendChar(0xAD);

sendChar(0x21);

sendChar(0x01);

How can i do it?

user3061597
  • 477
  • 1
  • 4
  • 8

1 Answers1

2

I did not tested this, there could be syntax errors:

int char2hex(char c){
   switch(c){
       case '0' : return 0x00;
       case '1' : return 0x01;
       case '2' : return 0x02;
       // until 9
       case 'A' : return 0x0a;
       case 'B' : return 0x0b;
       case 'C' : return 0x0c;
       // until F
   }
   return -1; // unknown char
}

void send(char str[]){
    if (!str)
        return;

    int i;
    for(i = 0; i < strlen(str); ++i)
        sendChar(char2hex(str[i]));
}

If you need more help, pls comment.

Update:

There could be many improvements, checking for NULL, put const around, checking for lowercase A,B,C,D,E,F etc.

You could even do something like - but test it prior use it:

int char2hex(char c){
   if (c < 'A')
      return c - '0';
   else
      return c - 'A' + 10;
}
chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256
Nick
  • 9,962
  • 4
  • 42
  • 80