牛骨文教育服务平台(让学习变的简单)
博文笔记

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

创建时间:2018-03-15 投稿人: 浏览次数:202
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;
}
声明:该文观点仅代表作者本人,牛骨文系教育信息发布平台,牛骨文仅提供信息存储空间服务。