Storing 2 hexadecimal characters in one byte in C

I have a string of characters, each of which is a hexadecimal value, for example:

unsigned char msg[] = "04FF";

I would like to store "04" in bytes and FF in another byte?

The output of desire should be like this,

unsigned short first_hex = 0x04; 
unsigned second_hex = 0xFF;

memcpy(hex_msg_p, &first_hex,1);
hex_msg_p++;
memcpy(hex_msg_p, &second_hex,1);
hex_msg_p++;

My line is very long and I really want to automate the process.

Thanks in advance

+3
source share
3 answers

Assuming your data is valid (ASCII, valid hexadecimal characters, correct length), you should be able to do something like this.

unsigned char *mkBytArray (char *s, int *len) {
    unsigned char *ret;

    *len = 0;
    if (*s == '\0') return NULL;
    ret = malloc (strlen (s) / 2);
    if (ret == NULL) return NULL;

    while (*s != '\0') {
        if (*s > '9')
            ret[*len] = ((tolower(*s) - 'a') + 10) << 4;
        else
            ret[*len] = (*s - '0') << 4;
        s++;
        if (*s > '9')
            ret[*len] |= tolower(*s) - 'a' + 10;
        else
            ret[*len] |= *s - '0';
        s++;
        *len++;
    }
    return ret;
}

This will give you an array of unsigned characters for which you are responsible for the release. It will also set the variable lento size so you can handle it easily.

, ASCII, , ISO , . .

+3

unsigned char msg[] = { 0x04, 0xFF };

, , :

usigned char result;
if (isdigit(string[i]))
  result = string[i]-'0';
else if (isupper(string[i]))
  result = string[i]-'A';
else if (islower(string[i]))
  result = string[i]-'a';

mutiply 16

+4
int first_hex, second_hex;

sscanf(msg,"%02X%02X", &first_hex, &second_hex);

Important: first_hexand second_hexmust have a type intthat will be used as in this example.

And if I understand correctly that you want to do the following:

char *pIn=msg;
char *pOut=hex_msg;
while(*pIn)
{
    int hex;
    if (*(pIn+1)==0)
    {
      // handle format error: odd number of hex digits
      ...
      break;
    }
    sscanf(pIn, "%02X", &hex);
    *pOut++=(char)hex;
    pIn+=2;
}
+2
source

Source: https://habr.com/ru/post/1774475/


All Articles