1

I am struggling to get a string to be understood as a hexstring during processing. I am writing a small program where I get an input ascii text as a hex string.

That is i read:

char *str = "313233";

This is actually 0x31, 0x32 and 0x33 which is actually the string "123".

I need an unsigned char array as follows:

unsigned char val[] = {0x31, 0x32, 0x33};

When I tried sscanf or sprintf, they expect integer array to be the destination pointer :(

That is, something like:

sprintf(str, "%2x", &val[0]);

How to do this? Perhaps this is very trivial but somehow I am confused.

Thanks.

4

1 回答 1

1

sscanf会成功的:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main(void)
{
    char *str = "313233";
    size_t i, n = strlen(str) / 2;
    unsigned char *v;

    v = malloc(n);
    if (v == NULL) {
        perror("malloc");
        exit(EXIT_FAILURE);
    }
    for (i = 0; i < n; i++)
        sscanf(str + (i * 2), "%2hhx", &v[i]);
    for (i = 0; i < n; i++)
        printf("0x%2x\n", v[i]);
    free(v);
    return 0;   
}
于 2013-07-30T12:14:37.330 回答