Convert a hexadecimal string to data

I have found many different solutions to this problem, but not all of them work, and many of them seem to be somewhat hacky and ineffective. Basically I have a string of hex data (ie "55 AA 41 2A 00 94 55 AA BB BB 00 FF") that I would like to convert to raw data. What's the best way to do this?

UPDATE : Vicky's solution worked great for me, but I changed it to work with hex strings that have no spaces in between and changed the style a bit.

int i = 0;
char *hexString = "55AA412A009455AABBBB00FF"
char *hexPtr = hexString;
unsigned int *result = calloc(strlen(hexString)/2 + 1, sizeof *result);

while (sscanf(hexPtr, "%02x", &result[i++])) {
    hexPtr += 2;
    if (hexPtr >= hexString + strlen(hexString)) break;
}

return result;

      

+2


a source to share


4 answers


Is the string always the same length?

If yes:

char *buf = "55 AA 41 2A 00 94 55 AA BB BB 00 FF";
sscanf(buf, "%x %x %x [repeat as many times as necessary]", &a, &b, &c [etc]);

      



If not:

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

int main (int argc, char ** argv)
{
    char *buf = "55 AA 41 2A 00 94 55 AA BB BB 00 FF";
    char *p = buf;
    int i = 0, j;
    unsigned int *result = calloc(strlen(buf)/3 + 1 * sizeof(int), 1);

    if (result)
    {
        while (sscanf(p, "%02x", &result[i++]))
        {
             p += 3;
            if (p > buf + strlen(buf))
            {
             break;
            }
        }

        printf("%s\n", buf);

        for (j = 0; j < i; j++)
        {
            printf("%02X ", result[j]);
        }

        printf("\n");
    }
}

      

+2


a source


Have you tried sscanf

or scanf

? This function processes hexadecimal values ​​and returns "raw data".



+1


a source


#define GETBITS(a) (a < 'A' ? a - '0' : toupper(a) - 'A' + 10)

char *cur;
char data;
for (cur = buffer; *cur; cur++) {
    data = GETBITS(cur[0]) << 4 + GETBITS(cur[1]);
    cur += 2;
    printf("%c", data);
}
printf("\n");

      

0


a source


while(input[i]!='\0'){        
    *(temp++) = ((input[i]>='0' && input[i]<='9')?(input[i]-'0'):(input[i]-'a'+10))*16 +( (input[i+1]>='0' && input[i]<='9')?(input[i+1]-'0'):(input[i+1]-'a'+10));
         i+=2;
}

      

0


a source







All Articles