Frozenfire
Frozenfire

Reputation: 37

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)

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?

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

does the number >> 1 mean that it removes the end number from the integer ex 1234 would be 123 in the recursive call?

Upvotes: 0

Views: 355

Answers (2)

Rakesh K
Rakesh K

Reputation: 8515

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). 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.

Upvotes: 0

sharptooth
sharptooth

Reputation: 170559

That >> has the same effect as division by 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.

You could use division with the same effect.

Upvotes: 1

Related Questions