如何将十进制值转换为二进制位?

时间:2018-08-16 15:47:27

标签: algorithm math binary decimal

基本上我想学习如何将十进制转换为二进制的算法,我发现了这一点:

int convert(int dec)
{
    if (dec == 0)
    {
        return 0;
    }
    else
    {
        return (dec % 2 + 10 * convert(dec / 2));
    }
}

它工作正常,但我听不懂dec % 2 + 10 * convert(dec / 2)。您能以一种易于理解的方式对基础数学的人进行转换吗?例如

首先执行哪种方法,二进制数dec = 50会变成110010

仅供参考:我可以这样做,50=(2^5=32)+(2^4=16)+(2^1)=50

谢谢。

4 个答案:

答案 0 :(得分:2)

我不会为您实现它,但是我很高兴描述算法并举一个例子。

从基数10转换为基数b最终遵循相同的一系列步骤,其中包括反复除以b,然后保存余数。

对于50(以base10为基准)到base2的情况,示例如下:

          Quotient  Remainder  
----------------------------
50 / 2 =  25        0
25 / 2 =  12        1
12 / 2 =   6        0
 6 / 2 =   3        0
 3 / 2 =   1        1 
 1 / 2 =   0        1

反向检查余数(从下到上)会以正确的b(在本例中为2)为代表:110010

有关为什么有效的信息,请查看以下问题:https://math.stackexchange.com/questions/86207/converting-decimalbase-10-numbers-to-binary-by-repeatedly-dividing-by-2

答案 1 :(得分:0)

让我们看一下dec % 2 + 10 * convert(dec / 2)。第一部分dec % 2是模运算,它决定一个数字应为1还是0。其余部分10 * convert(dec / 2)查找下一个(递归的)数字并将其放在当前数字的左侧。

通过稍微修改代码,您可以很容易地看到发生了什么。将else更改为:

else
{
    int ret = (dec % 2 + 10 * convert(dec / 2));
    printf("%d %d\n", dec, ret);
    return ret;
}

然后convert(50)将打印此内容:

$ ./a.out 
1 1
3 11
6 110
12 1100
25 11001
50 110010

但是正如评论中指出的那样,这不是真正的基本转换。您已将数字50转换为看起来完全像二进制表示形式的数字

答案 2 :(得分:0)

一种算法,该算法将给定整数N,以字符串S的形式表示二进制表示的N。

do
{
    if N is odd
    {
        add '1' to the beginning of S
    }
    else
    {
        add '0' to the beginning of S
    }
    divide N by 2
}
while N is non-zero

使用请求的示例:

initially N=50 and S is empty
50 is even: S="0"
divide N by 2: N=25
25 is odd: S="10"
divide N by 2: N=12
12 is even: S="010"
divide N by 2: N=6
6 is even: S="0010"
divide N by 2: N=3
3 is odd: S="10010"
divide N by 2: N=1
1 is odd: S="110010"
divide N by 2: N=0
stop looping

答案 3 :(得分:0)

string fullText = 0;

int convert(int dec)

{

if (dec == 0)
{
    fullText +=0;
}
else
{
    fullText += dec % 2;//mod
    dec = dec/2;
    return (convert(dec)));
}

} Console.Write(“ Binar Form:” + fullText);

也许您现在可以理解

相关问题