C fromHex 十六进制字符串转字节

const unsigned char *fromhex(const char *str)
{
    static unsigned char buf[512];
    size_t len = strlen(str) / 2;
    if (len > 512) len = 512;
    for (size_t i = 0; i < len; i++) {
        unsigned char c = 0;
        if (str[i * 2] >= '0' && str[i*2] <= '9') 
            c += (str[i * 2] - '0') << 4;
        if ((str[i * 2] & ~0x20) >= 'A' && (str[i*2] & ~0x20) <= 'F') 
            c += (10 + (str[i * 2] & ~0x20) - 'A') << 4;
        if (str[i * 2 + 1] >= '0' && str[i * 2 + 1] <= '9') 
            c += (str[i * 2 + 1] - '0');
        if ((str[i * 2 + 1] & ~0x20) >= 'A' && (str[i * 2 + 1] & ~0x20) <= 'F')
            c += (10 + (str[i * 2 + 1] & ~0x20) - 'A');
        buf[i] = c;
    }
    return buf;
}

你可能感兴趣的:(C/C++)