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
    0x31 is not the hex of 31 Commented Jul 30, 2013 at 11:27
  • 2
    there is a similar question on stackoverflow wich my help: stackoverflow.com/questions/3408706/… Commented Jul 30, 2013 at 11:29
  • @DavidRF true, but in my case, I get a hexinput as a string and therefore I know for sure the string is a hex string :) Commented Jul 30, 2013 at 11:46
  • 1
    sscanf(str, "%2hhx%2hhx%2hhx", &val[0], &val[1], &val[2]); Commented Jul 30, 2013 at 12:02

1 Answer 1

1

sscanf will do the trick:

#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;   
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.