我需要执行一个函数,将字符串从它提供给我们的基数转换为十进制数。
Ex : someone give me a string in base hexa and I need to make it decimal
我应该将字符在基数中的位置乘以幂乘以基数的长度吗?
类似这样的
Indexbase * ( lenghtbase^power)
然后我添加所有内容来完成我的号码?
最佳答案
您遵循此代码:
int hexadecimalToDecimal(char hexVal[])
{
int len = strlen(hexVal);
// Initializing base value to 1, i.e 16^0
int base = 1;
int dec_val = 0;
// Extracting characters as digits from last character
for (int i=len-1; i>=0; i--)
{
// if character lies in '0'-'9', converting
// it to integral 0-9 by subtracting 48 from
// ASCII value.
if (hexVal[i]>='0' && hexVal[i]<='9')
{
dec_val += (hexVal[i] - 48)*base;
// incrementing base by power
base = base * 16;
}
// if character lies in 'A'-'F' , converting
// it to integral 10 - 15 by subtracting 55
// from ASCII value
else if (hexVal[i]>='A' && hexVal[i]<='F')
{
dec_val += (hexVal[i] - 55)*base;
// incrementing base by power
base = base*16;
}
}
return dec_val;
}
关于c - 执行一个将字符串从基数转换为 int 的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57320694/