简体   繁体   中英

Convert hexidecimal char array to u8 array in C

Right now I have a u8 array that I successfully converted to a hexidecimal char array. Now, trying to change it back into a u8 array has been a doozy. I tried this code:

        // DEMO:
        char *message = "0f236a1f";
        int i;
        u8 final[4];
        memset(final, 0, 4);
        char* part = "00";
        for (i = 0; i < 4; i++)
        {
            memcpy(part, &message[i*2], 2);
            u8 num = 0;
            sscanf(part, "%x", &num);
            printf("%i", num); 
            final[i] = num;
        }

I prepopulate everything with values to prevent stay memory values from messing up large portions of zeros I have in my actual data. Despite everything I have tried, occasionally the wrong values are assigned, and I can't find any other method online which does the same thing. Help me if you can, I hate C.

EDIT:

I revised my code, and am showing the real thing now, to see if it helps. The variable message is 464 zeros in a giant char * array. The console is still occasionally printing numbers besides zero, not sure why:

        int i;
        u8 final[232];
        memset(final, 0, 232);
        char part[3] = "00";
        part[2] = 0;
        for (i = 0; i < 232; i++)
        {
            memcpy(part, &message[i*2], 2);
            unsigned int num = 0;
            sscanf(part, "%x", &num);
            printf("%i", num); 
            final[i] = (u8)num;
        }

You are creating undefined behavior with these lines:

    char* part = "00";
    for (i = 0; i < 4; i++)
    {
        memcpy(part, &message[i*2], 2);
        ...
        sscanf(part, "%x", &num);

part points to read only memory (this is why with strings like this we usually declare them as const char* to cause a compiler error when modification attempts occur) More info here.

You should allocate enough space for your string and null terminator with:

char part[3] = "00";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM