1

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

3 Answers 3

4

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;
    }
}

Demo on ideone.

0
2

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 }
0
1
#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;
}
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.