Search code examples
ccharipv6uint8t

converting char* to array of uint8_t (c)


I can make function calls and receive an array of strings that represents ipv6 adress. it looks something like this

char* buffer=resolver_getstring(config, INI_BOOT_MESHINTFIPADDRESS);

if i printed buffer i will gate the ipv6 adress in string form:

dddd:0000:0000:0000:0000:0000:0000:cccc

however, the way how ipv6 address is represented in my project is with 16 hexadecimal number by using uint8_t datatype as follows

uint8_t ipadress[16]

now my problem is how can i cast (or copy the memory of buffer) to uint8_t[16]

what i would like to get is

    ipadress[0]=dd // hexadecimal number
    ipaddress[1]=dd
    ....
    ipaddress[15]=cc

is there anyway i could do ? Regards,


Solution

  • #include <stdint.h>
    #include <inttypes.h>
    ...
    char *buffer="dddd:0000:0000:0000:0000:0000:0000:cccc";
    uint8_t ipadress[16];
    sscanf(buffer,
        "%2" SCNx8 "%2" SCNx8 ":"
        "%2" SCNx8 "%2" SCNx8 ":"
        "%2" SCNx8 "%2" SCNx8 ":"
        "%2" SCNx8 "%2" SCNx8 ":"
        "%2" SCNx8 "%2" SCNx8 ":"
        "%2" SCNx8 "%2" SCNx8 ":"
        "%2" SCNx8 "%2" SCNx8 ":"
        "%2" SCNx8 "%2" SCNx8 ,
        &ipadress[0],&ipadress[1],
        &ipadress[2],&ipadress[3],
        &ipadress[4],&ipadress[5],
        &ipadress[6],&ipadress[7],
        &ipadress[8],&ipadress[9],
        &ipadress[10],&ipadress[11],
        &ipadress[12],&ipadress[13],
        &ipadress[14],&ipadress[15]);