简体   繁体   English

C ++十进制到二进制混淆

[英]c++ Decimal to binary confusion

I've solved this problem in Java and used Integer.toBinaryString() however a function like that isn't available in c++ (to my knowledge) 我已经用Java解决了这个问题,并使用了Integer.toBinaryString()但是据我所知,像这样的函数在c ++中不可用。

I've got this function made and it works completely however I am confused WHY it works, any help would be greatly appreciated 我已经完成了此功能,并且可以完全正常工作,但是我很困惑为什么会起作用,任何帮助将不胜感激

void decimalToBinary (int number)
{
    int remainder;
    if (number <= 1)
    {
        cout << number;
        return;
    }
    remainder = number % 2;
    decimalToBinary(number >> 1);
    cout << remainder;
}

My main problem in understanding is the recursive call, why does it need number >> 1 in there? 我理解的主要问题是递归调用,为什么那里需要number >> 1

because when it is initially called it uses number, and checks if it is <=1 in that case it just outputs the number (0/1) and ends the function, otherwise it takes the number and gets the remainder from dividing by 2 (1/0) then calls the function again with number >> 1 因为在最初调用它时会使用数字,并在这种情况下检查它是否<= 1才输出数字(0/1)并结束该函数,否则它将获取该数字并从2除以余数( 1/0),然后用number >> 1再次调用该函数

does the number >> 1 mean that it removes the end number from the integer ex 1234 would be 123 in the recursive call? number >> 1number >> 1表示它从整数ex 1234中删除结束号在递归调用中将为123?

That >> has the same effect as division by 2. >>与除以2的效果相同。

The number is stored as binary, so shifting it right by one bit pushes that bit out and this has the effect of dividing the number by 2 just the same way as if you would shift a decimal number by one to the right you'd have it divided by 10. 该数字以二进制形式存储,因此将其右移一位会将其推出,这具有将数字除以2的效果,就像您将十进制数字向右移一位一样它除以10。

You could use division with the same effect. 您可以使用除法具有相同的效果。

The >> operator basically shifts the bits to the right by the number of times given as the argument to it, and it basically is equal to dividing the number by power of 2 times that argument (x/2^n). >>运算符基本上将这些位向右移动作为其自变量的次数,它基本上等于将该数除以该自变量的2倍的幂(x / 2 ^ n)。 To convert a decimal number to binary, you need to divide the number recursively by 2 until there's no more division possible - in this case when it's less than 1. And on the way you have to collect the reminders in each such division, which is effectively the binary number you want to get. 要将十进制数字转换为二进制,您需要将数字递归除以2,直到不再有可能的除法-在这种情况下,该数字小于1。在这种方式下,您必须在每个此类除法中收集提醒有效地获得您想要的二进制数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM