Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting decimal to binary in Java

I'm trying to write a code that converts a number to binary, and this is what I wrote. It gives me couple of errors in Eclipse, which I don't understand. What's wrong with that? Any other suggestions? I'd like to learn and hear for any comments for fixing it. Thank you.

public class NumberConverte {
  public static void main(String[] args) {
    int i = Integer.parseInt(args);
    public static void Binary(int int1){
      System.out.println(int1 + "in binary is");
      do {
        System.out.println(i mod 2);
      } while (int1>0);
    }
  }
}

The error messages:

  1. The method parseInt(String) in the type Integer is not applicable for the arguments (String[])
  2. Multiple markers at this line
    • Syntax error on token "(", ; expected
    • Syntax error on token ")", ; expected
    • void is an invalid type for the variable Binary
  3. Multiple markers at this line
    • Syntax error on token "mod", invalid AssignmentOperator
    • Syntax error on token "mod", invalid AssignmentOperator.
like image 349
Unknown user Avatar asked Mar 05 '11 13:03

Unknown user


5 Answers

Integer.toBinaryString(int) should do the trick !

And by the way, correct your syntax, if you're using Eclipse I'm sure he's complaining about a lot of error.

Working code :

public class NumberConverter {
   public static void main(String[] args) {
       int i = Integer.parseInt(args[0]);
       toBinary(i);
   }

   public static void toBinary(int int1){
       System.out.println(int1 + " in binary is");
       System.out.println(Integer.toBinaryString(int1));
   }
}
like image 70
krtek Avatar answered Oct 17 '22 18:10

krtek


Maybe you don't want to use toBinaryString(). You said that you are learning at the moment, so you can do it yourself like this:

/*
  F:\>java A 123
  123
    1  1  0  1  1  1  1  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0
  0  0  0  0  0  0
*/

public class A {
    public static void main(String[] args) {

        int a = Integer.parseInt(args[0]);
        System.out.println(a);

        int bit=1;
        for(int i=0; i<32; i++) {
            System.out.print("  "+(((a&bit)==0)?0:1));
            bit*=2;
        }
    }
}
like image 39
Bernd Elkemann Avatar answered Oct 17 '22 18:10

Bernd Elkemann


I suggest you get your program to compile first in your IDE. If you are not using an IDE I suggest you get a free one. This will show you where your errors are and I suggest you correct the errors until it compiles before worring about how to improve it.

like image 23
Peter Lawrey Avatar answered Oct 17 '22 19:10

Peter Lawrey


There are a two main issues you need to address:

  • Don't declare a method inside another method.
  • Your loop will never end.

For the first, people have already pointed out how to write that method. Note that normal method names in java are usually spelled with the first letter lowercase.

For the second, you're never changing the value of int1, so you'll end up printing the LSB of the input in a tight loop. Try something like:

do {
  System.out.println(int1 & 1);
  int1 = int1 >> 1;
} while (int1 > 0);

Explanation:

  • int1 & 1: that's a binary and. It "selects" the smallest bit (LSB), i.e. (a & 1) is one for odd numbers, zero for even numbers.
  • int1 >> 1: that's a right shift. It moves all the bits down one slot (>> 3 would move down 3 slots). LSB (bit 0) is discarded, bit 1 becomes LSB, bit 2 becomes bit one, etc... (a>>0) does nothing at all, leaves a intact.

Then you'll notice that you're printing the digits in the "wrong order" - it's more natural to have them printed MSB to LSB. You're outputting in reverse. To fix that, you'll probably be better off with a for loop, checking each bit from MSB to LSB.

The idea for the for loop would be to look at each of the 32 bits in the int, starting with the MSB so that they are printed left to right. Something like this

for (i=31; i>=0; i--) {
  if (int1 & (1<<i)) {
    // i-th bit is set
    System.out.print("1");
  } else {
    // i-th bit is clear
    System.out.print("0");
  }
}

1<<i is a left shift. Similar to the right shift, but in the other direction. (I haven't tested this at all.)

Once you get that to work, I suggest as a further exercise that you try doing the same thing but do not print out the leading zeroes.

like image 1
Mat Avatar answered Oct 17 '22 20:10

Mat


For starters you've declared a method inside a method. The main method is the method that runs first when you run your class. ParseInt takes a string, whereas args is an Array of strings, so we need to take the first (0-based) index of the array.

mod is not a valid operator, the syntax you wanted was %

You can use System.out.print to print on the same line rather than println

Try these corrections and let me know how you get on:

 public class NumberConverter {
  public static void main(String[] args) {
  int i = Integer.parseInt(args[0]);
  Binary(i);
 } 

 public static void Binary(int int1){
    System.out.println(int1 + " in binary is ");
    do {
        System.out.print(int1 % 2);
        int1 /= 2;
    } while (int1 > 0);


 }
}
like image 1
TimCodes.NET Avatar answered Oct 17 '22 19:10

TimCodes.NET