我第一次尝试将K&R 2-3的十六进制整数化为htoi

如何解决我第一次尝试将K&R 2-3的十六进制整数化为htoi

| 我正在通过K&R独自学习C。   2-3编写函数htoi(s),该函数将转换为十六进制字符串   位(包括可选的0x或0X)转换为等效整数值。   允许的数字是0到9,a到f和A到F。 我选择将每个有效数字转换为等效的0-15,并忽略无效字符。 我尝试不使用前46页中未介绍的任何内容。 在正确使用htoi()之前,我一直使用静态输入。
#include <stdio.h>
#include <ctype.h>
#include <string.h>

int htoi(char s[]);
// hex alpha char to integer
// 0..1 and Aa - fF
int hatoi(char c);

int main()
{
    char s[] = \"0xfff\";
    int res; /* result */
    res = htoi(s);
    printf(\"%s = %d\\n\",s,res);
    return 0;
}

int hatoi(char c)
{
  int res;
  if (isdigit(c))
    res = c - \'0\';
  else if (c >= \'a\' && c <= \'f\')
    /* offset a..f to 10-14 */
    res = (c - \'0\')-39;
  else if (c >= \'A\' && c <= \'F\')
    /* offset a..f to 10-14 */
    res = (c - \'0\')-7;
  else
    res = 0;
  return res;
}

int htoi(char s[])
{
  int len,i,result,power,digit;
  result = power = 0;

  len = strlen(s)-1;

  for (i=len; i >= 0; --i) {
    digit = hatoi(s[i]);
    if (digit) {
      if (power == 0) {
        result += digit;
        power++;
      } else
        result += digit * power;
      power *= 16;
    }
  }
  return result;
}
我靠近吗?看来一切正常。我想确保我没有学到不良习惯,并且在第二章中掌握了自己应该做的事情。     

解决方法

一些想法: 如果您的字符串的中间包含一个“ 1”,则您的代码将无效。考虑您正在对返回值
hatoi
进行的测试。 数字
39
7
似乎有点魔术。如果可以在代码中显式派生它们,那就更清楚了。 最好始终将代码块放在5或6后面的括号中,即使这只是一条语句。 为什么不将ѭ7初始化为ѭ8?这样,您就不需要在循环中使用这种特殊情况的逻辑。     ,我将
int
用作
hatoi()
参数:
int hatoi(int ch);
您无法区分有效的
\'0\'
和无效的字符ѭ10character。
htoi()
功能可以简化很多。例如,没有必要进行“ 15”测试(您从strlen-1循环到开始)。     ,总的来说,这看起来不错。我会为我认为可以改进的内容添加一些注释。
int hatoi(char c)
{
  int res;
  if (isdigit(c))
    res = c - \'0\';
没有真正的理由创建一个
res
变量。您总是返回在该变量中设置的任何内容,而永远不会对其进行更改。为什么不将
res = c - \'0\'
和后来的
return res
换成
return c - 0
  else if (c >= \'a\' && c <= \'f\')
    /* offset a..f to 10-14 */
    res = (c - \'0\')-39;
这似乎有些令人费解。为什么要减去
\'0\'
然后减去
39
?说“ 24”会更清楚。另外,评论有误,应该说“ 25”。
  result = power = 0;

  len = strlen(s)-1;

  for (i=len; i >= 0; --i) {
您的循环在整个字符串上运行;但在类似
0xabcd
的十六进制字符串中,
0x
可能不应该被视为您正在解析的数字的一部分。将未知字符视为0的处理方式与测试字符串无关紧要,但是如果您在开始时使用其他内容(例如
1230xabcd
),则会得到相当奇怪的结果。我建议检查一下前两个字符实际上是
0x
(如果不是,可能返回
0
),然后循环到down32ѭ,而不是down1。
    digit = hatoi(s[i]);
    if (digit) {
如果数字不为零,您似乎只会增加ѭ7。因此,对于like36ѭ这样的数字,您将得到18,而不是正确的结果258。不需要.15ѭ检查。如果要在无效字符的情况下从ѭ2返回一个标记以忽略它们,我建议返回ѭ39,然后选中ѭ40。
      if (power == 0) {
        result += digit;
        power++;
如果将
power
初始化为
1
而不是
0
,则不必具有这种特殊情况。
      } else
        result += digit * power;
      power *= 16;
    }
  }
    ,
isdigit
是否限于0-9,还是受语言环境影响?不想后者。
res = (c - \'0\')-39;
应该是
res = (c - \'a\')+10;
res = (c - \'0\')-7;
应该是
res = (c - \'A\')+10;
请注意,这仅适用于基于ASCII的计算机。在EBCDIC机器上,数字和/或字母不是连续的。 参数应为“ 51”指针。
htoi
非常复杂。您会发现
num = (num << 4) | digit;
非常有用。
int htoi(const char *s)
{
   int result = 0;
   while (*s)
      result = ( result << 4 ) | hatoi(*(s++));
   return result;
}
您可能要检查溢出。     ,
int hatoi(char c); /*** I\'d suggest a longer,descriptive name
                        such as parse_hexdigit ***/

int main()
{
    char s[] = \"0xfff\"; /*** Is this a good test case?
                             It is a palindrome with no numbers 0-9 ***/
    …
}

int hatoi(char c)
{
  int res;
  if (isdigit(c))
    res = c - \'0\';
  else if (c >= \'a\' && c <= \'f\')
    /* offset a..f to 10-14 */ /*** 10 - 15 ***/
    res = (c - \'0\')-39; /*** res = c - \'a\' + 10 is clearer ***/
  else if (c >= \'A\' && c <= \'F\')
    /* offset a..f to 10-14 */
    res = (c - \'0\')-7; /*** res = c - \'A\' + 10 is clearer ***/
  else
    res = 0;
  return res;
}

int htoi(char s[])
{
  int len,i,result,power,digit;
  result = power = 0;

  len = strlen(s)-1; /*** Check for overflow when you can ***/

  for (i=len; i >= 0; --i) { /*** Avoid iterating backwards ***/
    digit = hatoi(s[i]);
    if (digit) {
      if (power == 0) {
        result += digit;
        power++;
      } else /*** Use a consistent pattern of braces ***/
        result += digit * power;
      power *= 16;
    }
  }
  return result;
}
我会这样写:
unsigned htoi( char *s ) {
    unsigned acc = 0;

    if ( * s != \'0\' ) return 0;
    ++ s;
    if ( * s != \'x\' || * s != \'X\' ) return 0;
    ++ s;

    /* Check that multiplication by 16 will not overflow */
    while ( acc < UINT_MAX / 16 ) {
        if ( * s >= \'0\' && * s <= \'9\' ) {
            acc *= 16;
            acc += * s - \'0\';
        } else if ( * s >= \'A\' && * s <= \'F\' ) {
            acc *= 16;
            acc += * s - \'A\' + 10;
        } else if ( * s >= \'a\' && * s <= \'f\' ) {
            acc *= 16;
            acc += * s - \'a\' + 10;
        } else {
            return acc; /* handles end of string or just end of number */
        }

        ++ s;
    }

    return acc;
}
    

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-
参考1 参考2 解决方案 # 点击安装源 协议选择 http:// 路径填写 mirrors.aliyun.com/centos/8.3.2011/BaseOS/x86_64/os URL类型 软件库URL 其他路径 # 版本 7 mirrors.aliyun.com/centos/7/os/x86
报错1 [root@slave1 data_mocker]# kafka-console-consumer.sh --bootstrap-server slave1:9092 --topic topic_db [2023-12-19 18:31:12,770] WARN [Consumer clie
错误1 # 重写数据 hive (edu)&gt; insert overwrite table dwd_trade_cart_add_inc &gt; select data.id, &gt; data.user_id, &gt; data.course_id, &gt; date_format(
错误1 hive (edu)&gt; insert into huanhuan values(1,&#39;haoge&#39;); Query ID = root_20240110071417_fe1517ad-3607-41f4-bdcf-d00b98ac443e Total jobs = 1
报错1:执行到如下就不执行了,没有显示Successfully registered new MBean. [root@slave1 bin]# /usr/local/software/flume-1.9.0/bin/flume-ng agent -n a1 -c /usr/local/softwa
虚拟及没有启动任何服务器查看jps会显示jps,如果没有显示任何东西 [root@slave2 ~]# jps 9647 Jps 解决方案 # 进入/tmp查看 [root@slave1 dfs]# cd /tmp [root@slave1 tmp]# ll 总用量 48 drwxr-xr-x. 2
报错1 hive&gt; show databases; OK Failed with exception java.io.IOException:java.lang.RuntimeException: Error in configuring object Time taken: 0.474 se
报错1 [root@localhost ~]# vim -bash: vim: 未找到命令 安装vim yum -y install vim* # 查看是否安装成功 [root@hadoop01 hadoop]# rpm -qa |grep vim vim-X11-7.4.629-8.el7_9.x
修改hadoop配置 vi /usr/local/software/hadoop-2.9.2/etc/hadoop/yarn-site.xml # 添加如下 &lt;configuration&gt; &lt;property&gt; &lt;name&gt;yarn.nodemanager.res