Megha
Megha

Reputation: 121

Converting int to string in java is giving the answer as 1

I converted a decimal integer to binary and that binary integer when I'm trying to convert to a string is giving me 1 as the answer always when it should give the value of the string.

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

        String m = Integer.toString(n);
         System.out.print(m);

Any corrections and suggestions would be much appreciated.

Thanks!

Upvotes: 3

Views: 93

Answers (2)

Konstantin Yovkov
Konstantin Yovkov

Reputation: 62864

On every loop step, you have these two statements:

b = a % 2;
n = b;

Think about why all the possible values of n are 0 and 1?

It's because n copies the value of b, which is the value of a modulo 2, which is always 0 or 1.

The last value of n will be the left-most bit of the binary representation of a, which will be always 1 (unless a is 0) and this is why you always get 1 when printing m.

Upvotes: 4

Peter Lawrey
Peter Lawrey

Reputation: 533530

When you use

n = b;

you are replacing the value of n each time. What you want it to accumulate the bits in n. The simplest way to do this is to use a StringBuilder.

StringBuilder sb = new StringBuilder();
while (a > 0) {
    int lowest = a & 1;
    sb.insert(0, lowest);
    a = a >>> 1; // shift the bits down by 1.
}

String m = sb.toString();
System.out.print(m);

This will do the same thing as Integer.toString(a, 2)

Upvotes: 2

Related Questions