小数到二进制转换器

时间:2011-01-31 09:26:31

标签: java

我想在java中创建一段代码,它将十进制值转换为二进制,而不使用内置的二进制转换器命令。

但它不起作用......

public class MainFrame {
public static void binary(int number) {

    String result = new String();

    int binaryValues[] = {1024, 512, 256, 128, 64, 32, 16, 8, 4, 2, 1};

    if (number == 0) {
        result = result + "0";
    } else if (number == 1) {
        result = result + "1";
    } else {
        for (int i = 0; i < 11; i++) {
            while(number >= binaryValues[i]) {
                if (number % binaryValues[i] >= 0) {
                    result = result + "1";
                    number -= binaryValues[i];
                } else {
                    result = result + "0";
    //              number -= binaryValues[i];
                }
            }
        }
    }

    System.out.println(result);
}

public static void main(String[] args) {
    binary(5);
}
}

3 个答案:

答案 0 :(得分:2)

对于ints&gt; = 0:

public class DecimalToBinary {

    public static void main(String[] args) {
        int dec = 127;
        StringBuilder binary = new StringBuilder();
        do {
            binary.insert(0, dec % 2);
            dec /= 2;
        } while (dec != 0);
        System.out.println(binary.toString());
    }
}

答案 1 :(得分:0)

从else块中删除此行:

number -= binaryValues[i];

原因:如果数字大于2 n ,那么您想添加0并且不想减去2 n

删除while语句,没有必要(除非所有数字都小于2 12 )。只需保持for循环和if / else。

最后,if条件不采用模数而是减去。以下适用于我:

for (int i = 0; i < 11; i++) {
    if (number - binaryValues[i] >= 0) {
        result = result + "1";
        number -= binaryValues[i];
    } else {
        result = result + "0";
    }
}

答案 2 :(得分:0)

import java.util.Scanner;
public class BinaryConversion {
public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
System.out.println("Enter a decimal number: ");
    int numerator = input.nextInt();
        int num = numerator;
        boolean runLoop = true;
    String digit = "";
    while(runLoop){
        int bin = numerator % 2;
    numerator = (numerator / 2);
    digit= bin+digit;
    if (numerator == 0) {
        break;
    }

    }
    input.close();
    System.out.println("The binary value of "+num+" is "+digit);
}
}