且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

十六进制字符串在C字节数组

更新时间:2022-03-16 06:06:29

据我所知,有没有标准功能这样做,但其实很简单通过以下方式来实现:

As far as I know, there's no standard function to do so, but it's simple to achieve in the following manner:

#include <stdio.h>

int main(int argc, char **argv)
{
    const char hexstring[] = "deadbeef10203040b00b1e50", *pos = hexstring;
    unsigned char val[12];
    size_t count = 0;

     /* WARNING: no sanitization or error-checking whatsoever */
    for(count = 0; count < sizeof(val)/sizeof(val[0]); count++) {
        sscanf(pos, "%2hhx", &val[count]);
        pos += 2;
    }

    printf("0x");
    for(count = 0; count < sizeof(val)/sizeof(val[0]); count++)
        printf("%02x", val[count]);
    printf("\n");

    return(0);
}

希望这有助于。

由于铝指出,在奇数的字符串中的十六进制数字的情况下,你必须确保你的起始0。例如preFIX它,字符串f00f5 将被评估为 {0XF0,为0x0F为0x05} 通过上面的例子错误,而不是正确的 {为0x0F ,为0x00,0xf5}

As Al pointed out, in case of an odd number of hex digits in the string, you have to make sure you prefix it with a starting 0. For example, the string "f00f5" will be evaluated as {0xf0, 0x0f, 0x05} erroneously by the above example, instead of the proper {0x0f, 0x00, 0xf5}.