How to turn a hex string into an unsigned char array?

后端 未结 7 1252
春和景丽
春和景丽 2020-11-27 06:05

For example, I have a cstring \"E8 48 D8 FF FF 8B 0D\" (including spaces) which needs to be converted into the equivalent unsigned char array {0xE8,0x48,0

7条回答
  •  余生分开走
    2020-11-27 06:47

    If you know the length of the string to be parsed beforehand (e.g. you are reading something from /proc) you can use sscanf with the 'hh' type modifier, which specifies that the next conversion is one of diouxX and the pointer to store it will be either signed char or unsigned char.

    // example: ipv6 address as seen in /proc/net/if_inet6:
    char myString[] = "fe80000000000000020c29fffe01bafb";
    unsigned char addressBytes[16];
    sscanf(myString, "%02hhx%02hhx%02hhx%02hhx%02hhx%02hhx%02hhx
    %02hhx%02hhx%02hhx%02hhx%02hhx%02hhx%02hhx%02hhx%02hhx", &addressBytes[0],
    &addressBytes[1], &addressBytes[2], &addressBytes[3], &addressBytes[4], 
    &addressBytes[5], &addressBytes[6], &addressBytes[7], &addressBytes[8], 
    &addressBytes[9], &addressBytes[10], addressBytes[11],&addressBytes[12],
    &addressBytes[13], &addressBytes[14], &addressBytes[15]);
    
    int i;
    for (i = 0; i < 16; i++){
        printf("addressBytes[%d] = %02x\n", i, addressBytes[i]);
    }
    

    Output:

    addressBytes[0] = fe
    addressBytes[1] = 80
    addressBytes[2] = 00
    addressBytes[3] = 00
    addressBytes[4] = 00
    addressBytes[5] = 00
    addressBytes[6] = 00
    addressBytes[7] = 00
    addressBytes[8] = 02
    addressBytes[9] = 0c
    addressBytes[10] = 29
    addressBytes[11] = ff
    addressBytes[12] = fe
    addressBytes[13] = 01
    addressBytes[14] = ba
    addressBytes[15] = fb
    

提交回复
热议问题