【问题标题】:C++: Converting Hexadecimal to DecimalC++:将十六进制转换为十进制
【发布时间】:2012-06-17 08:55:19
【问题描述】:

我正在寻找一种将hex(十六进制) 轻松转换为dec(十进制) 的方法。我找到了一个简单的方法来做到这一点:

int k = 0x265;
cout << k << endl;

但是我不能输入265。无论如何它是否可以这样工作:

输入:265

输出:613

有没有办法做到这一点?

注意:我试过了:

int k = 0x, b;
cin >> b;
cout << k + b << endl;

它不起作用。

【问题讨论】:

标签: c++ algorithm hex decimal


【解决方案1】:

使用std::hex操纵器:

#include <iostream>
#include <iomanip>

int main()
{
    int x;
    std::cin >> std::hex >> x;
    std::cout << x << std::endl;

    return 0;
}

【讨论】:

  • 无论如何不使用输入来做到这一点?因为我想将原始输入用于其他用途
  • @zeulb,不确定你的意思。但是您将cin 还原为使用std::cin &gt;&gt; std::dec; 的小数
  • 我的意思是我想在两个不同的变量上同时使用十六进制和十进制
  • 输入的完成方式(十六进制或十进制)对 int 变量的内部表示没有任何影响,那又如何呢?请更清楚地表达自己。是否要将流中的值存储到同一语句中的两个变量??
  • 就像我使用'cin >> hex >> k;',然后我输入265,现在k值为613。我想要将265存储在变量p上。并且 613 停留在变量 k 上。对不起我的英语不好。
【解决方案2】:
#include <iostream>
#include <iomanip>
#include <sstream>

int main()
{
    int x, y;
    std::stringstream stream;

    std::cin >> x;
    stream << x;
    stream >> std::hex >> y;
    std::cout << y;

    return 0;
}

【讨论】:

  • 为什么是中间字符串流。为什么不简单地cin &gt;&gt; hex &gt;&gt; y
  • 你不需要#include 吗?
【解决方案3】:

嗯,C 方式可能类似于 ...

#include <stdlib.h>
#include <stdio.h>

int main()
{
        int n;
        scanf("%d", &n);
        printf("%X", n);

        exit(0);
}

【讨论】:

    【解决方案4】:

    这是一个使用字符串并使用 ASCII 表将其转换为十进制的解决方案:

    #include <iostream>
    #include <string>
    #include "math.h"
    using namespace std;
    unsigned long hex2dec(string hex)
    {
        unsigned long result = 0;
        for (int i=0; i<hex.length(); i++) {
            if (hex[i]>=48 && hex[i]<=57)
            {
                result += (hex[i]-48)*pow(16,hex.length()-i-1);
            } else if (hex[i]>=65 && hex[i]<=70) {
                result += (hex[i]-55)*pow(16,hex.length( )-i-1);
            } else if (hex[i]>=97 && hex[i]<=102) {
                result += (hex[i]-87)*pow(16,hex.length()-i-1);
            }
        }
        return result;
    }
    
    int main(int argc, const char * argv[]) {
        string hex_str;
        cin >> hex_str;
        cout << hex2dec(hex_str) << endl;
        return 0;
    }
    

    【讨论】:

      【解决方案5】:

      我用这个:

      template <typename T>
      bool fromHex(const std::string& hexValue, T& result)
      {
          std::stringstream ss;
          ss << std::hex << hexValue;
          ss >> result;
      
          return !ss.fail();
      }
      

      【讨论】:

        【解决方案6】:
            std::cout << "Enter decimal number: " ;
            std::cin >> input ;
        
            std::cout << "0x" << std::hex << input << '\n' ;
        

        如果您添加的输入可以是 boolean 或 float 或 int,它将在 int main 函数调用中传回...

        使用函数模板,C 根据参数类型生成单独的函数来适当地处理每种类型的调用。所有函数模板定义都以关键字模板开头,后跟用尖括号 括起来的参数。单个形式参数 T 用于要测试的数据类型。

        考虑以下程序,要求用户输入一个整数,然后输入一个浮点数,每个程序都使用 square 函数来确定平方。 使用函数模板,基于参数类型,C 生成单独的函数来适当地处理每种类型的调用。所有函数模板定义都以关键字模板开头,后跟用尖括号 括起来的参数。单个形式参数 T 用于要测试的数据类型。

        考虑以下程序,其中要求用户输入一个整数,然后输入一个浮点数,每个程序都使用 square 函数来确定平方。

        #include <iostream>
         using namespace std;
        template <class T>      // function template
        T square(T);    /* returns a value of type T and accepts                  type T     (int or float or whatever) */
          void main()
        {
        int x, y;
        float w, z;
        cout << "Enter a integer:  ";
        cin >> x;
        y = square(x);
        cout << "The square of that number is:  " << y << endl;
        cout << "Enter a float:  ";
        cin >> w;
        z = square(w);
        cout << "The square of that number is:  " << z << endl;
        }
        
        template <class T>      // function template
        T square(T u) //accepts a parameter u of type T (int or float)
        {
        return u * u;
        }
        
        Here is the output:
        
        Enter a integer:  5
        The square of that number is:  25
        Enter a float:  5.3
        The square of that number is:  28.09
        

        【讨论】:

          【解决方案7】:

          这应该也可以。

          #include <ctype.h>
          #include <string.h>
          
          template<typename T = unsigned int>
          T Hex2Int(const char* const Hexstr, bool* Overflow)
          {
              if (!Hexstr)
                  return false;
              if (Overflow)
                  *Overflow = false;
          
              auto between = [](char val, char c1, char c2) { return val >= c1 && val <= c2; };
              size_t len = strlen(Hexstr);
              T result = 0;
          
              for (size_t i = 0, offset = sizeof(T) << 3; i < len && (int)offset > 0; i++)
              {
                  if (between(Hexstr[i], '0', '9'))
                      result = result << 4 ^ Hexstr[i] - '0';
                  else if (between(tolower(Hexstr[i]), 'a', 'f'))
                      result = result << 4 ^ tolower(Hexstr[i]) - ('a' - 10); // Remove the decimal part;
                  offset -= 4;
              }
              if (((len + ((len % 2) != 0)) << 2) > (sizeof(T) << 3) && Overflow)
                  *Overflow = true;
              return result;
          }
          

          “溢出”参数是可选的,因此您可以将其保留为 NULL。

          例子:

          auto result = Hex2Int("C0ffee", NULL);
          auto result2 = Hex2Int<long>("DeadC0ffe", NULL);
          

          【讨论】:

            【解决方案8】:

            只使用:

            cout &lt;&lt; dec &lt;&lt; 0x;

            【讨论】:

              猜你喜欢
              • 2017-07-31
              • 2013-07-20
              • 1970-01-01
              • 2011-07-28
              • 1970-01-01
              • 2018-11-18
              • 2011-08-04
              相关资源
              最近更新 更多