十进制到二进制(反之亦然)

Decimal to binary (and vice-versa)(十进制到二进制(反之亦然))

本文介绍了十进制到二进制(反之亦然)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

谁能给出一个c++代码的例子,可以很容易地将十进制值转换为二进制,并将二进制值转换为十进制?

Can anybody give an example of c++ code that can easily convert a decimal value to binary and a binary value to decimal please?

推荐答案

嗯,你的问题真的很模糊,所以这个答案是一样的.

Well, your question is really vague, so this answer is the same.

string DecToBin(int number)
{
    if ( number == 0 ) return "0";
    if ( number == 1 ) return "1";

    if ( number % 2 == 0 )
        return DecToBin(number / 2) + "0";
    else
        return DecToBin(number / 2) + "1";
}

int BinToDec(string number)
{
    int result = 0, pow = 1;
    for ( int i = number.length() - 1; i >= 0; --i, pow <<= 1 )
        result += (number[i] - '0') * pow;

    return result;
}

您当然应该检查溢出并进行输入验证.

You should check for overflow and do input validation of course.

<代码>x <<1 == x * 2

这是一种转换为二进制的方法,它使用更类似编程"的方法而不是类似数学"的方法,因为缺乏更好的描述(尽管两者实际上是相同的,因为这个只是替换了除法右移,按位取模,循环递归.这是另一种思考方式,因为这表明您正在提取单个位).

Here's a way to convert to binary that uses a more "programming-like" approach rather than a "math-like" approach, for lack of a better description (the two are actually identical though, since this one just replaces divisions by right shifts, modulo by a bitwise and, recursion with a loop. It's kind of another way of thinking about it though, since this makes it obvious you are extracting the individual bits).

string DecToBin2(int number)
{
    string result = "";

    do
    {
        if ( (number & 1) == 0 )
            result += "0";
        else
            result += "1";

        number >>= 1;
    } while ( number );

    reverse(result.begin(), result.end());
    return result;
}

下面是如何在纸上进行转换:

And here is how to do the conversion on paper:

  1. 十进制转二进制
  2. 二进制转十进制

这篇关于十进制到二进制(反之亦然)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:十进制到二进制(反之亦然)

基础教程推荐