Chinaunix首页 | 论坛 | 博客
  • 博客访问: 2547250
  • 博文数量: 308
  • 博客积分: 5547
  • 博客等级: 大校
  • 技术积分: 3782
  • 用 户 组: 普通用户
  • 注册时间: 2009-11-24 09:47
个人简介

hello world.

文章分类

全部博文(308)

分类: C/C++

2010-08-11 15:59:13

    写一函数,输入一个十六进制数,输出相应的十进制数。
    由于十六进制中含有A,B,C,D,E,F字符,因此我们需要把这些字符变成我们需要的十进制数据,按照16进制换算为10进制的原则进行,由于进制的换算,一般从末尾开始,因此我们的程序也是从后面往前面进行运算最后算出结果。代码如下:
 

#include <stdio.h>
#include <math.h>

int OX2Ten(char[]);
int Char2Int(char);
int main(int argc,char *argv[])
{
    char ch[10];
    int result;
    printf("please input a HEX number:");
    gets(ch);
    result = OX2Ten(ch);
    if (-1 != result)
    {
       printf("the result is : %d",result);
    }
    else
    {
        printf("error: you input HEX number is error.");
    }
    system("pause");
    return 0;
}

int OX2Ten(char ch[])
{
    int i,j = 0;
    int result = 0,int10value;
    for (i = strlen(ch) - 1; i >= 0 ;i--,j++)
    {
        int10value = Char2Int(ch[i]);
        if (-1 != int10value)
        {
           result += pow(16,j) * int10value;
        }
        else
        {
            result = -1;
            break;
        }
    }
    return result;
}

int Char2Int(char c)
{
    int result = -1;
    if ((c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F'))
    {
       switch(c)
       {
                case 'a':
                case 'A':
                     result = 10;
                     break;
                case 'b':
                case 'B':
                     result = 11;
                     break;
                case 'c':
                case 'C':
                     result = 12;
                     break;
                case 'd':
                case 'D':
                     result = 13;
                     break;
                case 'e':
                case 'E':
                     result = 14;
                     break;
                case 'f':
                case 'F':
                     result = 15;
                     break;
       }
    }
    else if (c >= '0' && c <= '9')
    {
         result = c - 48 ;
    }
    else
    {
         ;
    }
    return result;
}


阅读(2075) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~