33

I am trying to convert decimal to binary numbers from the user's input using Java.

I'm getting errors.

package reversedBinary;
import java.util.Scanner;

public class ReversedBinary {


public static void main(String[] args) {
    int number; 

    Scanner in = new Scanner(System.in);

    System.out.println("Enter a positive integer");
    number=in.nextInt();

    if (number <0)
        System.out.println("Error: Not a positive integer");
    else { 

        System.out.print("Convert to binary is:");
        System.out.print(binaryform(number));
}

}

private static Object binaryform(int number) {
    int remainder;

    if (number <=1) {
        System.out.print(number);

    }

    remainder= number %2; 
    binaryform(number >>1);
    System.out.print(remainder);

    { 
    return null;
} } }

How do I convert Decimal to Binary in Java?

Eric Leschinski
  • 146,994
  • 96
  • 417
  • 335
Euridice01
  • 2,510
  • 11
  • 44
  • 76
  • 3
    If you see errors, you'll want to share them with us. – Hovercraft Full Of Eels Feb 09 '13 at 03:33
  • For some reason, it compiles but I don't see it print out the binary form @_@ It looks like here for some reason: Enter a positive integer 2 Convert to binary is:1000000 (forever zeroes..) Exception in thread "main" java.lang.StackOverflowError at java.io.PrintStream.write(Unknown Source) at java.io.PrintStream.print(Unknown Source) at reversedBinary.ReversedBinary.binaryform(ReversedBinary.java:30) at reversedBinary.ReversedBinary.binaryform(ReversedBinary.java:36) at – Euridice01 Feb 09 '13 at 03:39
  • Long.toBinaryString(Double.doubleToRawLongBits(d)); Reference http://stackoverflow.com/questions/6359847/convert-double-to-binary-representation – DotNetRussell Feb 09 '13 at 03:33
  • 1
    Possible duplicate of [Converting an int to a binary string representation in Java?](http://stackoverflow.com/questions/2406432/converting-an-int-to-a-binary-string-representation-in-java) – Erfan Dec 19 '15 at 08:01
  • There is no decimal here. The input is already binary. All you're doing is changing the representation, probably to ASCII. Unclear what you're asking. – user207421 Apr 06 '17 at 23:47
  • The simplest solution would be to built in method mentioned in this [link](https://stackoverflow.com/a/25958884/2077554) – Hemanth Kumar Mar 03 '18 at 23:36

26 Answers26

86

Integer.toBinaryString() is an in-built method and will do quite well.

skuntsel
  • 11,624
  • 11
  • 44
  • 67
Vaibhav
  • 1,094
  • 2
  • 9
  • 17
  • 2
    it should be noted that the leading 0s are eliminated from the outputs. – tony9099 Dec 07 '14 at 10:52
  • 4
    @tony9099 - Leading zero(s) are known as dummy bits. There will be no difference in actual value whatsoever and you can place zero as much as you want. for eg - binary of 111 or 00111 will give you same decimal number 7. – Vaibhav Dec 14 '14 at 17:25
42
Integer.toString(n,8) // decimal to octal

Integer.toString(n,2) // decimal to binary

Integer.toString(n,16) //decimal to Hex

where n = decimal number.

Jesse Pinkman
  • 429
  • 4
  • 2
  • is there a way to get the `binary string` in a fixed number of bits like, decimal `8` in `8bit` binary which `00001000` – Kasun Siyambalapitiya Jun 06 '16 at 15:29
  • 1
    @KasunSiyambalapitiya Just concatenate `String bin = "00000000" + Integer.toString(n,2)` then substring the desired length `bin.substring(0,8)` – Jaec Sep 19 '16 at 07:26
  • @JessePinkman after substring again `00000000` comes as this is concatenating `Strings`. the result of the `Integer.toString(n,2)` get appends after the `00000000`? – Kasun Siyambalapitiya Sep 19 '16 at 12:41
  • None of these methods converts decimal to anything. They all convert binary integers to something else. – user207421 Jun 17 '17 at 10:22
13

Your binaryForm method is getting caught in an infinite recursion, you need to return if number <= 1:

import java.util.Scanner;

public class ReversedBinary {

    public static void main(String[] args) {
        int number;

        Scanner in = new Scanner(System.in);

        System.out.println("Enter a positive integer");
        number = in.nextInt();

        if (number < 0) {
            System.out.println("Error: Not a positive integer");
        } else {

            System.out.print("Convert to binary is:");
            //System.out.print(binaryform(number));
            printBinaryform(number);
        }
    }

    private static void printBinaryform(int number) {
        int remainder;

        if (number <= 1) {
            System.out.print(number);
            return; // KICK OUT OF THE RECURSION
        }

        remainder = number % 2;
        printBinaryform(number >> 1);
        System.out.print(remainder);
    }
}
cerbin
  • 1,180
  • 15
  • 31
tlehman
  • 5,125
  • 2
  • 33
  • 51
  • Thank you!!! Also, I realized if I add the return null to get out of the loop. IF for instance, I entered 2 to convert to binary, the output is 10null.... Which is there a null there and how can I fix it? – Euridice01 Feb 09 '13 at 03:47
  • No problem. Notice that you are printing the value of `binaryForm(number)`, when it terminates, `null` is returned. You need to make an `Object`, set it's value to `binaryForm(number)` and then only print it if the value is not null. – tlehman Feb 09 '13 at 04:04
  • Could you give me an example? – Euridice01 Feb 09 '13 at 04:35
  • It is getting caught in an infinite *recursion,* not an infinite loop. – user207421 Feb 09 '13 at 09:26
  • Okay got it to work. Now, I'm having trouble reversing binary number to get it to decimal. Any ideas? :( – Euridice01 Feb 09 '13 at 16:42
  • @EJP Abstractly, this is a loop, implemented with recursion. However, when using a language with looping constructs like `for` and `while`, the distinction becomes more important, I corrected my post. – tlehman Feb 09 '13 at 16:42
  • @Euridice01 If you would like an example of using if statements in Java, see Oracle's documentation: http://docs.oracle.com/javase/tutorial/java/nutsandbolts/if.html – tlehman Feb 09 '13 at 16:43
  • There's no reason for this method to return anything, as its job is to print. – user207421 Jun 24 '13 at 23:17
  • And finally this code does not convert decimal to binary. It converts binary to an ASCII representation of binary. – user207421 Jun 17 '17 at 08:01
6

I just want to add, for anyone who uses:

   String x=Integer.toBinaryString()

to get a String of Binary numbers and wants to convert that string into an int. If you use

  int y=Integer.parseInt(x)

you will get a NumberFormatException error.

What I did to convert String x to Integers, was first converted each individual Char in the String x to a single Char in a for loop.

  char t = (x.charAt(z));

I then converted each Char back into an individual String,

  String u=String.valueOf(t);

then Parsed each String into an Integer.

Id figure Id post this, because I took me a while to figure out how to get a binary such as 01010101 into Integer form.

Tyson
  • 65
  • 1
  • 2
4
/**
 * @param no
 *            : Decimal no
 * @return binary as integer array
 */
public int[] convertBinary(int no) {
    int i = 0, temp[] = new int[7];
    int binary[];
    while (no > 0) {
        temp[i++] = no % 2;
        no /= 2;
    }
    binary = new int[i];
    int k = 0;
    for (int j = i - 1; j >= 0; j--) {
        binary[k++] = temp[j];
    }

    return binary;
}
loknath
  • 1,362
  • 16
  • 25
  • This converts a binary integer to an array of integers containing 0 or 1. Not decimal to binary. Not what was asked for. – user207421 Jun 17 '17 at 10:23
3
public static void main(String h[])
{
    Scanner sc=new Scanner(System.in);
    int decimal=sc.nextInt();
    
    String binary="";
    
    if(decimal<=0)
    {
        System.out.println("Please Enter greater than 0");
        
    }
    else
    {
        while(decimal>0)
        {
            
            binary=(decimal%2)+binary;
            decimal=decimal/2;
                                        
        }
        System.out.println("binary is:"+binary);
        
    }

}
  • There are no decimal numbers here, and no decimal to binary conversion. All you are doing is converting binary to binary. Quite pointless. – user207421 Feb 18 '18 at 00:23
  • @kohei..please degug the above code first..it will get the input from command line as decimal number..seen Scanner class used for this – Venkatesh Bandarapu Mar 01 '18 at 06:45
1

The following converts decimal to Binary with Time Complexity : O(n) Linear Time and with out any java inbuilt function

private static int decimalToBinary(int N) {
    StringBuilder builder = new StringBuilder();
    int base = 2;
    while (N != 0) {
        int reminder = N % base;
        builder.append(reminder);
        N = N / base;
    }

    return Integer.parseInt(builder.reverse().toString());
}
0

If you want to reverse the calculated binary form , you can use the StringBuffer class and simply use the reverse() method . Here is a sample program that will explain its use and calculate the binary

public class Binary {

    public StringBuffer calculateBinary(int number) {
        StringBuffer sBuf = new StringBuffer();
        int temp = 0;
        while (number > 0) {
            temp = number % 2;
            sBuf.append(temp);
            number = number / 2;
        }
        return sBuf.reverse();
    }
}


public class Main {

    public static void main(String[] args) throws IOException {
        System.out.println("enter the number you want to convert");
        BufferedReader bReader = new BufferedReader(newInputStreamReader(System.in));
        int number = Integer.parseInt(bReader.readLine());

        Binary binaryObject = new Binary();
        StringBuffer result = binaryObject.calculateBinary(number);
        System.out.println(result);
    }
}
Joy Bits
  • 33
  • 3
Sam
  • 9
  • 1
0

It might seem silly , but if u wanna try utility function

System.out.println(Integer.parseInt((Integer.toString(i,2))));

there must be some utility method to do it directly, I cant remember.

user207421
  • 305,947
  • 44
  • 307
  • 483
user3123372
  • 704
  • 1
  • 10
  • 26
  • Either you can't remember it, in which case this is not an answer, or you've just posted it, in which case your answer is self-contradictory. Which is it? – user207421 Sep 17 '14 at 01:07
  • The above method will just solve the purpose , but its kind of funny way to do it, but again its simple too. And there might be some utility method (ready made java api method), which I am not sure. – user3123372 Dec 06 '15 at 20:09
  • This converts a binary integer, not a decimal number. – user207421 Jun 17 '17 at 10:27
0

In C# , but it's just the same as in Java :

public static void findOnes2(int num)
{
    int count = 0;      // count 1's 
    String snum = "";   // final binary representation
    int rem = 0;        // remainder

    while (num != 0)
    {
        rem = num % 2;           // grab remainder
        snum += rem.ToString();  // build the binary rep
        num = num / 2;
        if (rem == 1)            // check if we have a 1 
            count++;             // if so add 1 to the count
    }

    char[] arr = snum.ToCharArray();
    Array.Reverse(arr);
    String snum2 = new string(arr);
    Console.WriteLine("Reporting ...");
    Console.WriteLine("The binary representation :" + snum2);
    Console.WriteLine("The number of 1's is :" + count);
}

public static void Main()
{
    findOnes2(10);
}
JAN
  • 21,236
  • 66
  • 181
  • 318
0
public static void main(String[] args)
{
    Scanner in =new Scanner(System.in);
    System.out.print("Put a number : ");
    int a=in.nextInt();
    StringBuffer b=new StringBuffer();
    while(a>=1)
    {
      if(a%2!=0)
      {
        b.append(1);
       }
      else if(a%2==0)
      {
         b.append(0);
      }
      a /=2;
    }
    System.out.println(b.reverse());
}
ProgramFOX
  • 6,131
  • 11
  • 45
  • 51
hassan
  • 11
  • 1
0

All your problems can be solved with a one-liner! To incorporate my solution into your project, simply remove your binaryform(int number) method, and replace System.out.print(binaryform(number)); with System.out.println(Integer.toBinaryString(number));.

Sir Jacob
  • 55
  • 8
0

Binary to Decimal without using Integer.ParseInt():

import java.util.Scanner;

//convert binary to decimal number in java without using Integer.parseInt() method.

public class BinaryToDecimalWithOutParseInt {

    public static void main(String[] args) {

        Scanner input = new Scanner( System.in );
        System.out.println("Enter a binary number: ");

        int  binarynum =input.nextInt();
        int binary=binarynum;

        int decimal = 0;
        int power = 0;

        while(true){

            if(binary == 0){

                break;

            } else {

                int temp = binary%10;
                decimal += temp*Math.pow(2, power);
                binary = binary/10;
                power++;

            }
        }
        System.out.println("Binary="+binarynum+" Decimal="+decimal); ;
    }

}

Output:

Enter a binary number:

1010

Binary=1010 Decimal=10


Binary to Decimal using Integer.parseInt():

import java.util.Scanner;

//convert binary to decimal number in java using Integer.parseInt() method.
public class BinaryToDecimalWithParseInt {

    public static void main(String[] args) {

        Scanner input = new Scanner( System.in );

        System.out.println("Enter a binary number: ");
        String binaryString =input.nextLine();

        System.out.println("Result: "+Integer.parseInt(binaryString,2));

    }

}

Output:

Enter a binary number:

1010

Result: 10

Tunaki
  • 132,869
  • 46
  • 340
  • 423
Sidarth
  • 69
  • 1
  • 4
  • 1
    Excessive promotion of a specific product/resource (that I removed here) may be perceived by the community as **spam**. Take a look at the [help], specially [What kind of behavior is expected of users?](http://stackoverflow.com/help/behavior)'s last section: _Avoid overt self-promotion_. You might also be interested in [How do I advertise on Stack Overflow?](http://stackoverflow.com/help/advertising). – Tunaki May 25 '16 at 12:17
  • `Scanner.nextInt()` converts decimal to binary. The rest of this does something else. – user207421 Jun 17 '17 at 10:23
0

A rather simple than efficient program, yet it does the job.

        Scanner sc = new Scanner(System.in);
        System.out.println("Give me my binaries");
        int str = sc.nextInt(2);
        System.out.println(str);
winnergo
  • 101
  • 11
0
public static String convertToBinary(int dec)
{
    String str = "";
    while(dec!=0)
    {
        str += Integer.toString(dec%2);
        dec /= 2;
    }
    return new StringBuffer(str).reverse().toString();
}
Anil
  • 655
  • 1
  • 11
  • 25
Xtrick
  • 21
  • 3
0
/**
 * converting decimal to binary
 *
 * @param n the number
 */
private static void toBinary(int n) {
    if (n == 0) {
        return; //end of recursion
    } else {
        toBinary(n / 2);
        System.out.print(n % 2);
    }
}

/**
 * converting decimal to binary string
 *
 * @param n the number
 * @return the binary string of n
 */
private static String toBinaryString(int n) {
    Stack<Integer> bits = new Stack<>();
    do {
        bits.push(n % 2);
        n /= 2;
    } while (n != 0);

    StringBuilder builder = new StringBuilder();
    while (!bits.isEmpty()) {
        builder.append(bits.pop());
    }
    return builder.toString();
}

Or you can use Integer.toString(int i, int radix)

e.g:(Convert 12 to binary)

Integer.toString(12, 2)
duyuanchao
  • 3,863
  • 1
  • 25
  • 16
0

Practically you can write it as a recursive function. Each function call returns their results and add to the tail of the previous result. It is possible to write this method by using java as simple as you can find below:

public class Solution {

    private static String convertDecimalToBinary(int n) {
        String output = "";
        if (n >= 1) {
            output = convertDecimalToBinary(n >> 1) + (n % 2);
        }

        return output;
    }

    public static void main(String[] args) {
        int num = 125;
        String binaryStr = convertDecimalToBinary(num);

        System.out.println(binaryStr);
    }

}

Let us take a look how is the above recursion working:

enter image description here

After calling convertDecimalToBinary method once, it calls itself till the value of the number will be lesser than 1 and return all of the concatenated results to the place where it called first.

References:

Java - Bitwise and Bit Shift Operators https://docs.oracle.com/javase/tutorial/java/nutsandbolts/op3.html

okanozeren
  • 555
  • 4
  • 10
0

The better way of doing it:

public static void main(String [] args) throws IOException {
        BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
        int t = Integer.parseInt(bf.readLine().trim());
        double ans = 0;
        int i=0;

        while(t!=0){
           int digit = t & 1;
           ans = ans + (digit*Math.pow(10,i));
           i++;
           t =t>>1;
        }
        System.out.println((int)ans);
    }
Procrastinator
  • 2,526
  • 30
  • 27
  • 36
-1

I just solved this myself, and I wanted to share my answer because it includes the binary reversal and then conversion to decimal. I'm not a very experienced coder but hopefully this will be helpful to someone else.

What I did was push the binary data onto a stack as I was converting it, and then popped it off to reverse it and convert it back to decimal.

import java.util.Scanner;
import java.util.Stack;

public class ReversedBinary 
{
    private Stack<Integer> st;

    public ReversedBinary()
    {
        st = new Stack<>();
    }

    private int decimaltoBinary(int dec)
    {
        if(dec == 0 || dec == 1)
        {
            st.push(dec % 2);
            return dec;
        }

        st.push(dec % 2);

        dec = decimaltoBinary(dec / 2);        

        return dec;
    }

    private int reversedtoDecimal()
    {
        int revDec = st.pop();
        int i = 1;

        while(!st.isEmpty())
        {
            revDec += st.pop() * Math.pow(2, i++);
        }

        return revDec;
    }

    public static void main(String[] args)
    {
        ReversedBinary rev = new ReversedBinary();

        System.out.println("Please enter a positive integer:");

        Scanner sc = new Scanner(System.in);
        while(sc.hasNextLine())
        {
            int input = Integer.parseInt(sc.nextLine());
            if(input < 1 || input > 1000000000)
            {
                System.out.println("Integer must be between 1 and 1000000000!");
            }
            else
            {
                rev.decimaltoBinary(input);
                System.out.println("Binary to reversed, converted to decimal: " + rev.reversedtoDecimal());
            }
        }

    }
}
-1
import java.util.*;

public class BinaryNumber 
{
    public static void main(String[] args)
    {
        Scanner scan = new Scanner(System.in);
        System.out.println("Enter the number");
        int n = scan.nextInt();
        int rem;
        int num =n; 
        String str="";
        while(num>0)
        {
            rem = num%2;
            str = rem + str;
            num=num/2;
        }
        System.out.println("the bunary number for "+n+" is : "+str);
    }
}
-1

This is a very basic procedure, I got this after putting a general procedure on paper.

import java.util.Scanner;

    public class DecimalToBinary {

        public static void main(String[] args) {
            Scanner input = new Scanner(System.in);
            System.out.println("Enter a Number:");
            int number = input.nextInt();
            while(number!=0)
            {
                if(number%2==0) 
                {
                    number/=2;
                    System.out.print(0);//Example: 10/2 = 5     -> 0
                }
                else if(number%2==1) 
                {
                    number/=2;
                    System.out.print(1);// 5/2 = 2              -> 1
                }
                else if(number==2)
                {
                    number/=2;
                    System.out.print(01);// 2/2 = 0             -> 01   ->0101
                }
            }
        }
    }
-1
//converts decimal to binary string
String convertToBinary(int decimalNumber){  
    String binary="";
    while(decimalNumber>0){
        int remainder=decimalNumber%2;
        //line below ensures the remainders are reversed
        binary=remainder+binary;
        decimalNumber=decimalNumber/2;
    }
    return binary;

}
vadotey
  • 1
  • 2
-1

One of the fastest solutions:

public static long getBinary(int n)
    {
        long res=0;
        int t=0;
        while(n>1)
        {
            t= (int) (Math.log(n)/Math.log(2));
            res = res+(long)(Math.pow(10, t));
            n-=Math.pow(2, t);
        }
        return res;
    }
-1

Even better with StringBuilder using insert() in front of the decimal string under construction, without calling reverse(),

static String toBinary(int n) {
    if (n == 0) {
        return "0";
    }

    StringBuilder bldr = new StringBuilder();
    while (n > 0) {
        bldr = bldr.insert(0, n % 2);
        n = n / 2;
    }

    return bldr.toString();
}
BJYC
  • 354
  • 2
  • 10
  • @EJP Read the original question carefully, not only the title of the post. The original question clearyly stated with example on how to convert an decimal integer into a binary. System.out.println("Enter a positive integer"); number = in.nextInt(); – BJYC Feb 23 '18 at 16:30
-2

No need of any java in-built functions. Simple recursion will do.

public class DecimaltoBinaryTest {
     public static void main(String[] args) {
        DecimaltoBinary decimaltoBinary = new DecimaltoBinary();
        System.out.println("hello " + decimaltoBinary.convertToBinary(1000,0));
    }

}

class DecimaltoBinary {

    public DecimaltoBinary() {
    }

    public int convertToBinary(int num,int binary) {
        if (num == 0 || num == 1) {
            return num;
        } 
        binary = convertToBinary(num / 2, binary);
        binary = binary * 10 + (num % 2);
        return binary;
    }
}
Seamus
  • 4,539
  • 2
  • 32
  • 42
-2
    int n = 13;
    String binary = "";

    //decimal to binary
    while (n > 0) {
        int d = n & 1;
        binary = d + binary;
        n = n >> 1;
    }
    System.out.println(binary);

    //binary to decimal
    int power = 1;
    n = 0;
    for (int i = binary.length() - 1; i >= 0; i--) {
        n = n + Character.getNumericValue(binary.charAt(i)) * power;
        power = power * 2;
    }

    System.out.println(n);
  • Hi brahmananda Kar, and thanks for the question. However remember that you are posting a new answer to a question which has existed for some time already, and has highly-rated answers. To make yours valuable in this context, you need to make it very high-quality; I recommend an [edit] to add some explanation of why this approach is better than the ones in the other answers. – Vince Bowdren Aug 27 '16 at 22:38
  • This converts a binary integer, not a decimal number. – user207421 Jun 17 '17 at 10:24