开发者

Storing 2 hex characters in one byte in C

I have a string of characters that开发者_如何转开发 every 2 characters represent a hex value, for example:

unsigned char msg[] = "04FF";

I would like to Store the "04" in on byte and the FF in another byte?

The desire output should be similar to 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 string is really long and i really would like to automate the process.

Thanks in advance


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

As for conversion from string, you need to read the string, two chars at a time:

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 by 16 and repeat


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

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 which you are responsible for freeing. It will also set the len variable to the size so that you can process it easily.

The reason it has to be ASCII is because ISO only mandates that numeric characters are consecutive. All bets are off for alphas.


int first_hex, second_hex;

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

Important: first_hex and second_hex must be of type int to be used like in this example.

And if I understand you right you want to do 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;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜