C++十进制转十六进制代码

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29759404/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 21:14:12  来源:igfitidea点击:

Decimal to hexadecimal conversion code in C++

c++

提问by user123

I'm a complete newbie to C++ programming. I've been given the task to code decimal to hexadecimal conversion. This is what I've done so far.

我是 C++ 编程的完全新手。我的任务是编写十进制到十六进制的转换。这是我到目前为止所做的。

#include <iostream>

int main()
{
    long dec;
    int rem;

    std::cout << "enter decimal number: ";
    std::cin >> dec;

    while (dec > 0) {
        rem = dec % 16;
        if (rem > 9) {
            switch (rem) {
               case 10: std::cout << "A"; break;
               case 11: std::cout << "B"; break;
               case 12: std::cout << "C"; break;
               case 13: std::cout << "D"; break;
               case 14: std::cout << "E"; break;
               case 15: std::cout << "F"; break;
            }
        }
        else {
            std::cout << rem;
        }
        dec = dec / 16;
    }
}

It gives answer backwards, like if I input a decimal number '650' it gives hexadecimal value A82when the answer should be 28A. Can anyone suggest what I should do to correct it?

它向后给出答案,就像我输入一个十进制数“650”一样,A82当答案应该是28A. 谁能建议我应该做些什么来纠正它?

回答by AdamF

The most simple solution:

最简单的解决方法:

#include <iostream>
using namespace std;
int main(){
    int val;
    cin >> val;
    cout << hex << val << endl;
    return 0;
}

The fix of your algorithm - use recursion:

您的算法的修复 - 使用递归:

#include <iostream>
#include <conio.h>
using namespace std;

void print_hex(int value)
{
    if (value == 0)
        return;

    int rem = value % 16;
    value /= 16;
    print_hex(value); //first execute recurency and print next value

    //after return print the less significant digit
    if (rem > 9)
        cout << (char)(rem - 10 + 'A');
    else
        cout << rem;
}

int main(int argc, char * argv[]) {
    cout << "enter decimal number: ";
    long dec;
    cin >> dec;
    print_hex(dec);
    cout << endl;
    return 0;
}

回答by Filip Kowalski

Of course it gives the answer backwards. Your program starts analizing the given decimal number "starting from the back". To be specific, you are converting the number starting with the least importantdigits. After each digit processed you output it immidiately. Thus you first output the least important digits, but both hexadecimal and decimal systems represent number starting with the most important ones. In other words if your number is XYZin hexadecimal (which represents 16^2 * X + 16^1 * Y + 16^0 * Zin decimal), you output it as ZYX. Try saving all digits in a string, adding new digits in the beggining of it:

当然,它倒着给出了答案。您的程序开始分析给定的十进制数“从后面开始”。具体来说,您正在转换以最不重要的数字开头的数字。处理完每个数字后,您立即将其输出。因此,您首先输出最不重要的数字,但十六进制和十进制系统都表示从最重要的数字开始的数字。换句话说,如果您的数字是XYZ十六进制(16^2 * X + 16^1 * Y + 16^0 * Z以十进制表示),则将其输出为ZYX. 尝试将所有数字保存在一个字符串中,在它的开头添加新数字:

string s = "";
while (dec > 0)   // Do this whilst the quotient is greater than 0.
{
  rem = dec % 16; // Get the remainder.
  if (rem > 9)
  {
    // Map the character given that the remainder is greater than 9.
    switch (rem)
    {
      case 10: s = "A" + s; break;
      case 11: s = "B" + s; break;
      case 12: s = "C" + s; break;
      case 13: s = "D" + s; break;
      case 14: s = "E" + s; break;
      case 15: s = "F" + s; break;
    }
  }
  else
  {
    s = char(rem + 48) + s; // Converts integer (0-9) to ASCII code.
    // x + 48 is the ASCII code for x digit (if 0 <= x <= 9)
  }
  dec = dec/16;
 }
 if (s == "") // if the number was 0, the string will remain empty
   cout << "0";
 else
   cout << s;

回答by jxh

If the only thing wrong is that the output is in the reverse order of what you want, you could place the output into a container instead. Then, reverse the order of the output in the container before printing it out.

如果唯一错误的是输出与您想要的顺序相反,您可以将输出放入容器中。然后,在打印之前反转容器中的输出顺序。

One way to do to get the output into a container is to send your output to a stringstream.

将输出放入容器的一种方法是将输出发送到stringstream.

std::ostringstream sout;
const char *hex = "0123456789ABCDEF";
while (dec > 0) {
    rem = dec % 16;
    sout << hex[rem];
    dec = dec / 16;
}
std::string s(sout.str());
std::reverse(s.begin(), s.end());
std::cout << s;

回答by FalconUA

The easiest way: Put it into a string:

最简单的方法:将其放入字符串中:

string answer = "";
while (dec > 0) {
    rem = dec % 16;
    if (rem > 9) {
        switch (rem) {
           case 10: answer = "A" + answer; break;
           case 11: answer = "B" + answer; break;
           case 12: answer = "C" + answer; break;
           case 13: answer = "D" + answer; break;
           case 14: answer = "E" + answer; break;
           case 15: answer = "F" + answer; break;
        }
    }
    else {
        answer = string(1, (char)rem-'0') + answer;
    }
    dec = dec / 16;
}
cout << answer;

回答by HippoEug

The solution if you want to convert from Decimal to Binary (Base 2), Hexadecimal (Base 16) etc!

如果您想从十进制转换为二进制(基数 2)、十六进制(基数 16)等的解决方案!

#include <iostream>
using namespace std;

void d2base(int n, int b);
char arr[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};

int main()
{
    int num, base;

    cout << "Enter decimal number to convert: ";
    cin >> num;
    cout << "Enter the base: ";
    cin >> base;
    cout << "\nNumber in " << base << " is ";

    d2base (num, base);
}

void d2base(int n, int b)
{
    if (n > 0)
    {
        d2base(n/b, b);
        cout << arr[n%b];
    }
}