Convert a hexadecimal string to an integer efficiently in C?

后端 未结 16 2217
暖寄归人
暖寄归人 2020-12-01 09:31

In C, what is the most efficient way to convert a string of hex digits into a binary unsigned int or unsigned long?

For example, if I have

16条回答
  •  一个人的身影
    2020-12-01 10:00

    @Eric

    I was actually hoping to see a C wizard post something really cool, sort of like what I did but less verbose, while still doing it "manually".

    Well, I'm no C guru, but here's what I came up with:

    unsigned int parseHex(const char * str)
    {
        unsigned int val = 0;
        char c;
    
        while(c = *str++)
        {
            val <<= 4;
    
            if (c >= '0' && c <= '9')
            {
                val += c & 0x0F;
                continue;
            }
    
            c &= 0xDF;
            if (c >= 'A' && c <= 'F')
            {
                val += (c & 0x07) + 9;
                continue;
            }
    
            errno = EINVAL;
            return 0;
        }
    
        return val;
    }
    

    I originally had more bitmasking going on instead of comparisons, but I seriously doubt bitmasking is any faster than comparison on modern hardware.

提交回复
热议问题