Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Storing 2 hex characters in one byte in C

Tags:

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

like image 974
Unis Avatar asked Jan 24 '26 06:01

Unis


2 Answers

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

like image 198
Šimon Tóth Avatar answered Jan 26 '26 23:01

Šimon Tóth


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.

like image 33
paxdiablo Avatar answered Jan 27 '26 00:01

paxdiablo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!