实例三十一:进制转换

实例三十一:进制转换

问题描述:
将一个十六进制数转换为相应的十进制数输出。
Converts a hexadecimal number to the corresponding decimal number output.

算法思路:

  • 十六进制某些数位不属于十进制整型数据,所以为了便于取出十六进制数的每个位数,应用字符串来表示一个十六进制数。
    Some digits in hexadecimal are not decimal integer data, so in order to easily take out each digit of a hexadecimal number, a string is used to represent a hexadecimal number.
  • 把十六进制数转换为十进制数,首先要把字符串转换为十进制数,且这个字符串必须是 0~9 与 a~f(或 A~F)这些字符组成的,因此,输入一个十六进制数时必须根据这个约束条件进行识别判断字符串(十六进制数)是否合法。
    To convert a hexadecimal number to a decimal number, first convert the string to a decimal number, and the string must be 0~9 and a~f (or A~F). Therefore, enter a ten. When the hexadecimal number is used, it is necessary to identify whether the character string (hexadecimal number) is legal according to this constraint.
#include <stdio.h>
#define MAX 100

int main(void)
{
    int htoi(char s[]);
    char t[MAX], c;
    int i=0,flag=0,flag1=1;
    printf("\nInput a hex number:");
    while((c=getchar())!='0'&&i<MAX&&flag1)
    {
        if((c>='0'&&c<='9')||(c>='a'&&c<='f')||(c>='A'&&c<='F'))
        {
            flag=1;
            t[i++]=c;
        }
        else if(flag)
        {
            t[i]='\0';
            printf("decimal number is %d\n",htoi(t));
            printf("continue or not?");
            c=getchar();
            if(c=='N'||c=='n')
                flag1=0;
            else
            {
                flag=0;
                i=0;
                printf("\nInput aa hex number:");
            }
        }
    }
    return 0;
}

int htoi(char s[])
{
    int i,n=0;
    for(i=0;s[i]!='\0';i++)
    {
        if(s[i]>='0'&&s[i]<='9')
            n=n*16+s[i]-'0';
        if(s[i]>='a'&&s[i]<='f')
            n=n*16+s[i]-'a'+10;
        if(s[i]>'A'&&s[i]<='F')
            n=n*16+s[i]-'A'+10;
    }
    return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值