I need to make a decimal to binary converter in Java. I can’t use Integer.toBinaryString() and every answer I’ve seen uses that. I need to actually make the algorithm. I want to keep the input an int and the output a String because if I change that the rest of the program this is from gets messed up. If you can, keep it pretty basic. This is what I’ve ended up with after hours of drafting and scrapping and there’s many things wrong with it, like it doesn’t even put together a binary number. Please, please help, I’m so confused and my brain is a mess.
public static String decToBin(int dec)
{
String bin = "";
int exp = 0;
for(int expLevel = 0; Math.pow(2, expLevel) <= dec; expLevel++)
{
if(dec - Math.pow(2, expLevel) >= 0)
{
dec -= Math.pow(2, expLevel-1);
}
}
return bin;
}
Looks like you need to review your math notes. Here’s a good explanation of the basic algorithm: How to Convert from Decimal to Binary.
If you check the provided link, you will see that you just need to get the remainder of the divisions of the number divided by 2. As a brief algorithm: