十六进制转十进制问题另外,如何将char数转换为实际的int数

如何解决十六进制转十进制问题另外,如何将char数转换为实际的int数

请帮我找出这个程序中的错误,对我来说它看起来是正确的,我已经检查过了,但它给出了错误的答案。 在这个程序中,我已经明确检查了 A、B、C、D、E、F,并根据它们各自的值。

[已编辑]:另外,这个问题与如何将字符数转换为实际整数有关。

#include<iostream>
#include<cmath>
#include<bits/stdc++.h>
using namespace std;
void convert(string num)
{
   long int last_digit;
    int s=num.length();
    int i;
    long long int result=0;
    reverse(num.begin(),num.end());                 
    for(i=0;i<s;i++)
    {
        if(num[i]=='a' || num[i]=='A')
        {
            last_digit=10;
            result+=last_digit*pow(16,i);
        }
        else if(num[i]=='b'|| num[i]=='B')
        {
            last_digit=11;
            result+=last_digit*pow(16,i);
        }
        else if(num[i]=='c' || num[i]=='C')
        {
            last_digit=12;
            result+=last_digit*pow(16,i);
        }
        else if(num[i]=='d'|| num[i]=='D' )
        {
            last_digit=13;
            result+=last_digit*pow(16,i);
        }
        else if(num[i]=='e'|| num[i]=='E' )
        {
            last_digit=14;
            result+=last_digit*pow(16,i);
        }
        else if(num[i]=='f' || num[i]=='F')
        {
            last_digit=15;
            result+=last_digit*pow(16,i);
        }
        else {
            last_digit=num[i];
        result+=last_digit*pow(16,i);
        }
    }
    cout<<result;
}
int main()
{
    string hexa;
    cout<<"Enter the hexadecimal number:";
    getline(cin,hexa);
    convert(hexa);
}

解决方法

您的代码非常复杂且错误。

你可能想要这个:

void int convert(string num)
{
  long int last_digit;
  int s = num.length();
  int i;
  long long int result = 0;

  for (i = 0; i < s; i++)
  {
    result <<= 4;                     // multiply by 16,using pow is overkill
    auto digit = toupper(num[i]);     // convert to upper case

    if (digit >= 'A' && digit <= 'F')
      last_digit = digit - 'A' + 10;   // digit is in range 'A'..'F'
    else
      last_digit = digit - '0';        // digit is (hopefully) in range '0'..'9'

    result += last_digit;
  }

  cout << result;
}

但这仍然不是很好:

  • 函数应该返回一个 long long int 而不是打印结果
  • 其他一些事情可以做得更优雅

所以更好的版本是这样的:

#include <iostream>
#include <string>

using namespace std;

long long int convert(const string & num)  // always pass objects as const & if possible
{
  long long int result = 0;

  for (const auto & ch : num)      // use range based for loops whenever possible
  {
    result <<= 4;
    auto digit = toupper(ch);

    long int last_digit;           // declare local variables in the inner most scope

    if (digit >= 'A' && digit <= 'F')
      last_digit = digit - 'A' + 10;
    else
      last_digit = digit - '0';

    result += last_digit;
  }

  return result;
}

int main()
{
  string hexa;
  cout << "Enter the hexadecimal number:";
  getline(cin,hexa);
  cout << convert(hexa);
}

由于上述代码假定要转换的字符串仅包含十六进制字符,因此仍有更多改进的空间。理想情况下,应该以某种方式检查无效字符。我把这个留作练习。

last_digit = digit - 'A' + 10; 假定字母 A 到 F 的代码是连续的,理论上可能并非如此。但是,您遇到并非这种情况的编码方案的可能性接近于零。当今使用的绝大多数计算机系统都使用 ASCII 编码方案,有些使用 EBCDIC,但是在这两种编码方案中,字母 A 到 F 的字符代码是连续的。我不知道今天使用的任何其他编码方案。

,

您的问题是在 else 情况下,您将 num[i]char 转换为其 ascii 等效项。因此,例如,如果您尝试转换 A0,则 0 会转换为 48 而不是 0。 要更正,您应该将 num[i] 转换为其等效的整数(而不是 asci)。

为此,请替换:

else {
            last_digit=num[i];
        result+=last_digit*pow(16,i);

  else {
            last_digit = num[i]-'0';
            result+=last_digit*pow(16,i);
    }

在新行中,last_digit = num[i]-'0';等价于last_digit = (int)num[i]-(int)'0';num[i]的表示码中减去'0'中任意一位数的表示码

之所以有效,是因为 C++ 标准保证 10 位十进制数字的数字表示是连续的且按递增顺序排列(official ref iso-cpp 并在 chapter 2.3paragraph 3 中说明

因此,如果您取任何一位数num[i]的表示(例如ascii代码)并用'0'的表示代码(ascii中的48)减去它,您将获得直接将数字本身作为整数值。

更正后的执行示例:

A0
160

F5
245

一个小的代码审查: 您正在用许多 result+=last_digit*pow(16,i); 重复自己。您只能在循环结束时执行一次。但那是另一回事。

,

您使问题变得过于复杂(std::pow 也有点慢)。 std::stoul 可以采用数字基数并自动为您转换为整数:

#include <string>
#include <iostream>

std::size_t char_count{0u};
std::string hexa{};
std::getline(std::cin,hexa);
hexa = "0x" + hexa;
unsigned long value_uint = std::stoul(hexa,&char_count,16);

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

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地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-