Is there any library available in "C" that will convert a hexadecimal to byte array in C
for e.g
Input const char *ptr="ff:ff:fe:ff"
There is a ":" deliminator value
You can use strtoll
function to do the conversion of individual bytes. The function takes a base
parameter as its third argument, and reports the new position in the input, letting you decide between skipping the delimiter and reading more data, or finishing the loop:
char *ptr="ff:ff:fe:ff";
for (;;) {
int res = strtol(ptr, &ptr, 16);
printf("%x\n", res);
if (*ptr == ':') {
ptr++;
} else {
break;
}
}
You probably could use sscanf() to read the values in.
#include <stdio.h>
int main() {
const char *input = "ff:ff:fe:ff";
unsigned int array[4];
int ret;
ret = sscanf(input, "%02x:%02x:%02x:%02x",
&array[0], &array[1], &array[2], &array[3]);
if (ret != 4) {
printf("Match failed.\n");
return -1;
}
printf("array = { %02x, %02x, %02x, %02x }\n",
array[0], array[1], array[2], array[3]);
return 0;
}
Output:
array = { ff, ff, fe, ff }
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#define h2i(x) (isdigit(x) ? (x) - '0' : tolower(x) - 'a' + 10)
int main(void){
const char *ptr="ff:ff:fe:ff";
size_t size = (strlen(ptr)+1)/3;
unsigned char byte[size];
int i;
for(i = 0; i < size; ++i){
byte[i] = h2i(ptr[i*3])*16 + h2i(ptr[i*3+1]);
//printf("%02x", byte[i]);//for check
}
return 0;
}