Converting a hex string to a byte array

后端 未结 19 2209
时光取名叫无心
时光取名叫无心 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:02

    If you want to use OpenSSL to do it, there is a nifty trick I found:

    BIGNUM *input = BN_new();
    int input_length = BN_hex2bn(&input, argv[2]);
    input_length = (input_length + 1) / 2; // BN_hex2bn() returns number of hex digits
    unsigned char *input_buffer = (unsigned char*)malloc(input_length);
    retval = BN_bn2bin(input, input_buffer);
    

    Just be sure to strip off any leading '0x' to the string.

提交回复
热议问题