Results 1 to 4 of 4
  1. #1
    Anindo is offline Member
    Join Date
    Jul 2009
    Posts
    4
    Rep Power
    0

    Question converting decimal to binary value using recursion in java

    Hello
    i am trying to make a recursive method that take a decimal number and convert it into its binary number. i think there will be two base cases that remainder is one or zero .can anyone help me further with simple solution

  2. #2
    javamadd is offline Member
    Join Date
    Jul 2009
    Posts
    4
    Rep Power
    0

    Default Simpler way to do the same

    import java.util.Scanner;


    public class toBinary {

    /**
    * @author : javamadd
    */
    public static void main(String[] args) {
    int num;
    System.out.println("enter the decimal number");
    Scanner scanboy = new Scanner(System.in);
    num = scanboy.nextInt();
    System.out.print("The decimal number is " + num);
    String binary = Integer.toBinaryString(num);
    System.out.print(" And the corresponding Binary is ");
    System.out.print( ""+ binary);
    }

    }

  3. #3
    Eranga's Avatar
    Eranga is offline Moderator
    Join Date
    Jul 2007
    Location
    Colombo, Sri Lanka
    Posts
    11,372
    Blog Entries
    1
    Rep Power
    19

    Default

    @OP, what you mean by recursive method? Can you explain bit more clearly. What javamadd explain is straightforward, no any recursive process going on.

  4. #4
    Hardik is offline Member
    Join Date
    Jul 2009
    Posts
    6
    Rep Power
    0

    Post Reccursion method to convert decimal to binary.

    hey here is the code :

    class Binary
    {
    int a1,b1;
    void convert(int a1)
    {
    b1 = a1 % 2;
    if(a1 > 0)
    {
    convert(a1/2);
    System.out.println("binary bits are = "+b1); //i think the result would you get reverse of the byte so u take care about it
    }
    }
    }
    class DECTOBIN
    {
    public static void main(String args[])
    {
    Binary obj = new Binary();
    obj.a1 = Integer.parseInt(args[0]);
    obj.convert(obj.a1);
    }
    }


    Ok well. this is the code. But i didnt try it.

Similar Threads

  1. Replies: 4
    Last Post: 10-26-2009, 10:17 PM
  2. Eclipse- Decimal to binary
    By queen_vee in forum New To Java
    Replies: 1
    Last Post: 02-24-2009, 02:17 PM
  3. Convert decimal to binary..pls help..newbie here
    By mephisto772 in forum New To Java
    Replies: 5
    Last Post: 02-12-2009, 08:17 AM
  4. Use recursion to convert binary to...
    By coco in forum Advanced Java
    Replies: 1
    Last Post: 08-07-2007, 07:46 AM
  5. Converts a binary number to a decimal
    By cachi in forum New To Java
    Replies: 1
    Last Post: 08-01-2007, 09:57 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •