Qaiser Mehmood
Qaiser Mehmood

Reputation: 975

Describe this function for Decimal to Binary conversion

I am unable to understand this why it prints the total binary bits instead of last bit in Java and C++.I checked it in C it present as I think i.e only last bit. However, in C++and java it prints all bits.

public static void main(String[] args) {

    toBin(2);
}// end of main

static void toBin(int b) {
    int modu = 0;

    if (b < 1) {
        return;
    }
    modu = b % 2;
    b=(b>>1);
    toBin(b);
    System.out.print(modu);       

}// end of toBin()

Upvotes: 0

Views: 249

Answers (4)

Reverend Gonzo
Reverend Gonzo

Reputation: 40851

The way toBin() works is that it first finds the remainer when divided by two

modu = b % 2;

adds that to the beginning, then divides by 2

b = b >> 1

and repeats recursively until there's nothing left.

if (b < 1) {
  return
}

If you think about it in terms of decimal, it's a little easier.

Say you have the number 4863, and you want to print it out in base 10.

First you take n % 10 which is 3, then you divide by 10, and you 486. Repeat, you have 6 and 48, and so.

The reason print is after toBin(b) is so it doesn't need to maintain a string. Instead, it'll print the most inner recursive call first, and as it exits out, it'll print the remaining ones in reverse.

Essentially, the following (which is probably easier to understand) does the same, but prints the digits backwards:

    while (b >= 1) {
        System.out.print(b % 2);
        b /= 2;
    }

Upvotes: 0

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726809

This code should do the same thing in all three languages: it prints all bits of a number recursively.

Let's work through what happens when you call toBin on the number 5:

modu of the first level of invocation is set to 1 (5%2)
    toBin is called on 2 (5>>1)
    modu of the second level of invocation is set to 0 (4%2)
    toBin is called on 1 (2>>1)
        modu of the third level of invocation is set to 1 (1%2)
        toBin is called on 0 (1>>1)
             toBin returns because b < 1
        modu of the third level is printed: 1; toBin returns
     modu of the second level is printed: 0; toBin returns
 modu of the first level is printed: 1; toBin returns

As the result, 101, the binary representation of 5, is printed.

Upvotes: 1

asaelr
asaelr

Reputation: 5456

In every call to toBin (except of the last one) you print a digit, so what do yo expect?

if you want to print just the last bit, you don't need recursion. just System.out.print(b%2)

Upvotes: 0

Carl Norum
Carl Norum

Reputation: 225032

Your program (with simple porting effort) works fine in C too... what's your question?

Upvotes: 0

Related Questions