Converting a hex string to a byte array

后端 未结 19 2145
时光取名叫无心
时光取名叫无心 2020-11-22 12:10

What is the best way to convert a variable length hex string e.g. \"01A1\" to a byte array containing that data.

i.e converting this:

st         


        
19条回答
  •  不知归路
    2020-11-22 13:09

    Somebody mentioned using sscanf to do this, but didn't say how. This is how. It's useful because it also works in ancient versions of C and C++ and even most versions of embedded C or C++ for microcontrollers.

    When converted to bytes, the hex-string in this example resolves to the ASCII text "Hello there!" which is then printed.

    #include 
    int main ()
    {
        char hexdata[] = "48656c6c6f20746865726521";
        char bytedata[20]{};
        for(int j = 0; j < sizeof(hexdata) / 2; j++) {
            sscanf(hexdata + j * 2, "%02hhX", bytedata + j);
        }
        printf ("%s -> %s\n", hexdata, bytedata);
        return 0;
    }
    

提交回复
热议问题