//standard header
#include //needed for power
/*function to convert hexadecimal to decimal*/
int hextodec(char bin[])
{
char *ptr;//pointer to a char
int value = 0; // the value of the current hex char pointed to
int sum = 0;// the running sum
int power = -1;//power is what base 16 is raised to starts at -1 to count for 0
ptr = bin;//set the pointer to point at start of string ie 0xabcd ptr += 2;//first digit after the 0x ie a
/*use this to work out the length of the hex number so any length
input can be calculated power is the length of the string*/
while(*ptr != (char)null)//while pointer is not null count a new char
{
ptr++;
power++;
}
ptr = &bin[2];//sets pointer to point at first value after 0x ie a
while(*ptr != (char)null)//while pointer is not equal to null
{
/*this switch statement is used to computer the current value
that the pointer points to using hex alphabet*/
switch(*ptr)
{
case '0': value = 0; break;
case '1': value = 1; break;
case '2': value = 2; break;
case '3': value = 3; break;
case '4': value = 4; break;
case '5': value = 5; break;
case '6': value = 6; break;
case '7': value = 7; break;
case '8': value = 8; break;
case '9': value = 9; break;
case 'a': value = 10; break;
case 'b': value = 11; break;
case 'c': value = 12; break;
case 'd': value = 13; break;
case 'e': value = 14; break;
case 'f': value = 15; break;
default: printf("input error not 0-9 or a-f"); exit(1);
}
sum += pow(16.0,power)*value;//this calculates the total until pointer points to null
ptr++;//moves the pointer along to the next char
power--;//decrements the power
}
printf("\nhex: 0x%x, decimal: %d ", sum, sum);
return sum;
}
void main()
{
char number[10], *p;//allows up to 8 bits of actual data ie 0z or 0x then 8 digits
printf("\nenter in the number with a preceding 0x if hex : ");
scanf("%s", &number);//get input
p = number;//point the char pointer to the char array
int buf;
if(*p == '0')//if first char is 0
{
p++;//increment
if(*p == 'x')//if second letter is x its a hex number
hextodec(number);//so call hextodec function
else//else its invalid input ie the 0 isnt followed by an x
printf("\ninvalid format");
}
else//else its invalid input dosnt start with 0 printf("\ninvalid format");
getch(); }
这篇博客介绍了如何在C语言中将带有0x前缀的十六进制数转换为十进制。通过编写一个名为`hextodec`的函数,该函数解析字符串,根据十六进制字符计算对应的十进制值,并返回总和。文章还提供了一个简单的主函数`main`来获取用户输入并调用`hextodec`进行转换。
2500

被折叠的 条评论
为什么被折叠?



