-1

我想将十进制数转换为二进制数并返回该二进制数。但是,我需要能够将这个二进制数表示为一个完整的int变量。我看到的示例和过去的问题仅分别返回 0 和 1,这是行不通的。

现在,我这样做的方式是将 0 和 1 存储在一个int数组中。有没有办法得到所有这些数组元素并形成一个int变量?或者还有其他更好的方法吗?我正在尝试尽可能少地调用 java 库(即很少的 parseInt() 等)

4

3 回答 3

-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();
                    }}
于 2013-03-11T12:40:28.507 回答
-1

Try this code:

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);
    }
}
于 2013-02-05T04:44:21.730 回答
-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/

于 2013-02-05T04:37:36.847 回答