C语言实现十六进制字符串转整形

函数:

//"81234" => 0x81234
//"aa55" => 0xaa55
/*
uint32_t value = 0;
str_to_hex("aa55", 4, &value);	//value = 0xaa55	
*/
int str_to_hex(uint8_t *str, uint8_t len, uint32_t *value)
{
    uint32_t tmp = 0;
    int i = 0;

    for(i = 0; i < len; i++)
    {
        if(!((str[i] >= '0' && str[i] <= '9') || (str[i] >= 'a' && str[i] <= 'f') || str[i] >= 'A' && str[i] <= 'F'))
        {
            printf("%s illegal\n");
            return -1;
        }
    }

    for (i = 0; i < len; i++)
    {
        tmp <<= 4;            //0x80
        if(str[i] >= '0' && str[i] <= '9')
            tmp |= (str[i] - '0');
        else if(str[i] >= 'a' && str[i] <= 'f')
            tmp |= str[i] - 'a' + 10;
        else if(str[i] >= 'A' && str[i] <= 'F')
            tmp |= str[i] - 'A' + 10;
    }

    *value = tmp;
//    printf("str = %s, value = %d\n", str, *value);

    return 0;
}

你可能感兴趣的:(c语言,java,Xilinx,FPGA)