满意答案
#include //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(); }
00分享举报