Converting a string with a hexadecimal representation of a number to an actual numeric value

前端 未结 6 928
渐次进展
渐次进展 2020-12-21 10:49

I have a string like this:

\"00c4\"

And I need to convert it to the numeric value that would be expressed by the literal:

0         


        
6条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-21 11:17

    int val_from_hex(char *hex_string) {
        char *c = hex_string;
        int val = 0;
        while(*c) {
            val <<= 4;
            if(*c >= '0' && *c <= '9')
                val += *c - '0';
            else if(*c >= 'a' && *c <= 'f')
                val += *c - 'a' + 10;
            c++;
        }
        return val;
    }
    

提交回复
热议问题