3

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!

Megha
  • 121
  • 1
  • 1
  • 9

2 Answers2

4

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.

Konstantin Yovkov
  • 62,134
  • 8
  • 100
  • 147
  • So basically just the last value of n is getting stored? Alright, got the problem, thanks! – Megha Dec 18 '15 at 16:14
2

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)

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130