《C程序设计语言》 练习2-3

问题描述

  练习2-3 编写函数htoi(s),把由16进制数字组成的字符串(包含可选的前缀0X或0x)转换成与之等价的整形值。字符串中允许包含的数字包括:0 ~ 9, a ~ f,A ~ F。

  Write the function htoi(s) , which converts a string of hexadecimal digits (including an optional 0x or 0X) into its equivalent integer value. The allowable digits are 0 through 9, a through f, and A through F .

 

解题思路

  1.就是输入十六进制,输出十进制

  2.首先写一个函数,把输入读入到一个数组中,我这里用我自己写的getlines实现,你也可以用for+scanf

  3.要判断输入的是否是十六进制,字符串只能是0~9、a~f、A~F

  4.转换公式:n = n * 16 + result;(后面详细接受这个公式什么意思,怎么推到来的)

 

代码如下

 

 1 #include<stdio.h>
 2 #define MAXLEN 1024
 3 #define YES 1//是十六进制
 4 #define NO 0//不是十六进制
 5 
 6 int htoi(char array[]);//进制转换函数
 7 int getlines(char array[],int maxlen);//字符串读取函数
 8 
 9 int main()
10 {
11     int len;//字符串长度
12     int ten_number;//十进制数
13     char array[MAXLEN];
14     while ((len = getlines(array,MAXLEN)) > 0)
15     {
16         ten_number = htoi(array);
17         printf("%d", ten_number);
18         putchar('\n');
19     }    
20     return 0;
21 }
22 
23 int getlines(char array[],int maxlen)
24 {
25     int c,i;
26     for (i = 0; i < maxlen-1 && (c = getchar())!=EOF && c!= '\n'; i++)
27     {
28         array[i] = c;
29     }
30     if (c=='\n')
31     {
32         array[i] = c;
33         i++;
34     }
35     array[i] = '\0';
36     return i;
37 }
38 
39 int htoi(char array[])
40 {
41     int i,n;
42     int result=0;
43     int state = YES;//判断是否是十六进制
44     i = 0;
45     if (array[i] == '0')
46     {
47         i++;
48         if (array[i]=='x' || array[i]=='X')
49         {
50             i++;
51         }
52     }
53     n = 0;
54     for ( ; state==YES; i++)
55     {
56         if (array[i] >= '0' && array[i] <= '9')
57         {
58             result = array[i] - '0';
59         }else if (array[i] >= 'A' && array[i] <= 'F')
60         {
61             result = array[i] - 'A' + 10;
62         }else if (array[i] >= 'a' && array[i] <= 'f')
63         {
64             result = array[i] - 'a' + 10;
65         }else
66         {
67             state = NO;
68         }
69         if(state== YES)
70         {    
71             n = n*16 + result;
72         }       
73     }
74     return n;

 

 

  OK,我们现在讲一下解题步骤中第四步那个公式的来源:

  如果你去百度或谷歌十六进制转换十进制,告诉你的方法都是从十六进制的最右端开始,乘以16的几次方一类的,这个方法适用于人,但是如果用C来实现,显得有点麻烦了,所以我才去了从高位开始转换,就是从最左端

  我举个十进制的例子,大家就会豁然开朗了

  比如有一个字符串‘2564’,他是十进制

  它等于什么?

  我们有那个公式来展开2564的话就是这样:

  2 * 10 + 5 = 25

  25 * 10 + 6 = 256

  256 * 10 + 4 = 2564

  因为是十进制所以我们乘以10,十六进制我们乘以16

 

posted @ 2020-05-09 16:36  骑码的佳俊  阅读(400)  评论(0编辑  收藏  举报