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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With