小数为二进制(反之亦然) [英] Decimal to binary (and vice-versa)

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

问题描述

任何人可以给出的C ++ code为例,可以很容易的十进制数转换为二进制和二进制值转换为十进制好吗?

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&LT;&LT; 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. 二进制到十进制

  1. Decimal to binary
  2. Binary to decimal

这篇关于小数为二进制(反之亦然)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆