我想将十进制数转换为二进制数并返回该二进制数。但是,我需要能够将此二进制数表示为一个完整的int
变量。我见过的例子和过去的问题只分别返回0和1,这是行不通的。
现在,我正在这样做的方式我将0和1存储在int
数组中。有没有办法获得所有这些数组元素并形成一个int
变量?或者还有另一种更好的方法吗?我正在尝试尽可能少的Java库调用(即很少有parseInt()等。)
答案 0 :(得分:-1)
尝试代码
import java.util.*;
public class number
{
public static void main (String [] args)
{
Scanner input = new Scanner (System.in);
System.out.println ("Input decimal number");
int decimal = input.nextInt ();
input.close ();
int base = 2;
int result = 0;
int multiplier = 1;
while (decimal>0)
{
int residue = decimal%base;
decimal = decimal/base;
result = result +residue*multiplier;
multiplier = multiplier * 10;
}
System.out.println ("binary....."+result);
}
}
了解更多信息http://forum.codecall.net/topic/54004-decimal-to-binary-number/
答案 1 :(得分:-1)
试试这段代码:
import java.lang.*;
import java.io.*;
public class BinaryToDecimal{
public static void main(String[] args) throws IOException{
BufferedReader bf= new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter the Binary value: ");
String str = bf.readLine();
long num = Long.parseLong(str);
long rem;
while(num > 0){
rem = num % 10;
num = num / 10;
if(rem != 0 && rem != 1){
System.out.println("This is not a binary number.");
System.out.println("Please try once again.");
System.exit(0);
}
}
int i= Integer.parseInt(str,2);
System.out.println("Decimal:="+ i);
}
}
答案 2 :(得分:-1)
经过测试的代码.........
private Double decToBin(int nm) {
String hex = "" + nm;
int i = Integer.parseInt(hex);
String by = Integer.toBinaryString(i);
System.out.println("Binary: " + by);
return Double.parseDouble(by);
}
写你需要的地方...... ??
else if (re.equals(" Bin ")) {
try {
String prev = data.get(i - 1);
result =decToBin(Integer.parseInt(prev));
re = "" + result;
i++;
twoValue = true;
} catch (Exception e) {
e.printStackTrace();
}}