Continue to Site

# Decimal to Binary In Java

Status
Not open for further replies.

#### HarshJain

##### Newbie
So I have code that will convert a decimal number to binary. I use a recursive algorithm for it, however, I cannot seem to get it to do what I want. Here is the code:

Code:
import java.util.*;

public static int toBinary(int a){

int bin = 0;
int remainder = 0;
if(a >= 1){
toBinary(a/2);
bin = (a%2);
}

return bin;

}

public static void main(String[] args){

System.out.println(toBinary(3));
System.out.print(toBinary(3));
}
}

So I want to return the binary solution so that I can save it as a variable in my main method. However, my current output would only give me that last digit of the binary number. I utilized the number 3 similarly as an experiment and I get 1 as a result for both print and println techniques. Why would that be, and how might I fix it?

Before trying this code I have done several research on the web and read a couple of articles on binary to decimal in java to understand the concept in a better way, my source of Information is Wiki, scaler, and GFG.

Much obliged!

Hi,

to be honest, I don´t understand what your code tries to do.

binary ... decimal ... hex ... ASCII ... are just phrases how a value is represented.
Usually you don´t need a conversion at all.

example: 0b01000001 = 65 = 0x41 = "A"
So it does not matter whether you store 0b01000001 or 65 to a memory ... the content will be the same. No need for a conversion.

Maybe you could give an example what´s your input value and output value.

Klaus

Status
Not open for further replies.