Converting decimal to binary in Java

59,656

Solution 1

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));
   }
}

Solution 2

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;
        }
    }
}

Solution 3

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


 }
}

Solution 4

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.

Solution 5

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.

Share:
59,656

Related videos on Youtube

Unknown user
Author by

Unknown user

Updated on November 18, 2020

Comments

  • Unknown user
    Unknown user over 3 years

    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.
    • TimCodes.NET
      TimCodes.NET about 13 years
      can you write what your input was and also what the error was, always helps speed things up
  • Unknown user
    Unknown user about 13 years
    sorry I ment "fixing", not "improving".
  • TimCodes.NET
    TimCodes.NET about 13 years
    Although that's not much help for learning to program in Java!
  • Unknown user
    Unknown user about 13 years
    Thank you chimoo for the comment! 1. Why do I have to put the [0] in the parseInt function? 2.Can I use "mod" Instead of &? 3.And now, after there's no syntax errors, it still says Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0 at NumberConverte.main(NumberConverte.java:4). How can I start my code? How do I input a string?
  • Unknown user
    Unknown user about 13 years
    Mat thank you. How can I use "for" loop in this case? What does "int1 = int1 >> 1;" do?
  • TimCodes.NET
    TimCodes.NET about 13 years
    1. the [0] is an index into the array (a collection of strings) 0 is the first 2. you can't use mod 3. you input a string by saying java NumberConverte 32
  • Unknown user
    Unknown user about 13 years
    where do i write that? I want to have the input from a user, is this for that?
  • TimCodes.NET
    TimCodes.NET about 13 years
    yes in the console, except i forgot your using eclipse, i don't know about eclipse, sorry. you mmight want to note the code for your binary method is wrong too, see other answers
  • Unknown user
    Unknown user about 13 years
    Another question. How do I get an input from a user? I probably should add something to the main function, Am I?
  • Dan-Dev
    Dan-Dev over 7 years
    Please take the time to add description to your answer please don't post code only answers
  • user207421
    user207421 over 7 years
    What exactly is this supposed to do?

Related