Problem: Write a program that will accept a positive integer number with a range of 8 to 256. The program should convert it to binary number. Display the result.
output:
Enter Number: 8
Binary Equivalent: 1000
Thanks!
Printable View
Problem: Write a program that will accept a positive integer number with a range of 8 to 256. The program should convert it to binary number. Display the result.
output:
Enter Number: 8
Binary Equivalent: 1000
Thanks!
try it first, then we'll help.
if you know the math algorithm then it should be easy ;)
but if you have problems with your code post it
Take a look at the Integer class and it's toBinaryString() method. ;-)
Edit: Although I'm sure, as this is homework, you are meant to do it on your own.
In any case, give it a try, and as already suggested, post your code if you have problems, we are not, however, going to do it for you, just so you know.
i've used binarystring but not really the requirement...:
import java.io.*;
public class DecimalToBinary{
public static void main(String args[]) throws IOException{
BufferedReader num = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter a decimal value (8 to 256):");
String x = num.readLine();
int i = Integer.parseInt(x);
String bin = Integer.toBinaryString(i);
System.out.println("Binary Equivalent: " + bin);
}
}
it should be the long cut method using functions like this:
function x [args]
args = args.toString();
if (args.length == 0)
return false;
for (var i = 0;i<args.length;i++)
{
if (args.substring(i,i+1) < "0" || args.substring(i, i+1) > "9")
{
return false;
}
}
return true;
}
{
res1 = 999;
args = arg;
while(args>1)
{
arg1 = parseInt(args/2);
arg2 = args%2;
args = arg1;
if(res1 == 999)
{
res1 = arg2.toString();
}
else
{
res1 = arg2.toString()+res1.toString();
}
}
if(args == 1 && res1 != 999)
{
res1 = args.toString()+res1.toString();
}
else if(args == 0 && res1 == 999)
{
res1 = 0;
}
else if(res1 == 999)
{
res1 = 1;
}
var ll = res1.length;
while(ll%4 != 0)
{
res1 = "0"+res1;
ll = res1.length;
}
return res1;
}
{
var sd = name.value;
if(isNum(sd))
{
var result = deciToBin(sd);
document.first.deciBin.value = result;
}
else
{
document.first.deci.value = sd.substring(0,sd.length-1) ;
}
}
Please repost your code (from your editor not by copying what you have already posted, as that has already had the formatting ruined) using code tags so the formatting is preserved. That, as it is, is only a pain to attempt to read, and can easily lead to misunderstood code, and, ipso facto, advice.