10 16 进制 转换 c语言,求一段 16进制转10进制 C语言代码。 被转换的16进制数是 0x**型,转换后为10进制数。...

满意答案

#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分享举报

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值