简单的十进制到二进制Java

时间:2016-11-07 04:21:26

标签: java

我们如何将int number(十进制)转换为二进制?我正在学习Java&有下面的代码。有什么建议?谢谢!

public static int decimalToBinary(int number) {
int result = 0;
while(number > 0){


    int mod = number % 2;
    result = result * 1 + mod;

    number /= 2;
}

return result;
}

2 个答案:

答案 0 :(得分:0)

这会将其打印到屏幕上,但您可以轻松地将其分配给变量。

import java.util.Scanner;

public class ReversedBinary {

    public static void main(String[] args) {
        int number; 

        Scanner in = new Scanner(System.in);

        System.out.println("Enter a positive integer");
        number = in.nextInt();

        if (number < 0) {
            System.out.println("Error: Not a positive integer");
        } else { 

            System.out.print("Convert to binary is:");
            //System.out.print(binaryform(number));
            printBinaryform(number);
        }
    }

    private static void printBinaryform(int number) {
        int remainder;

        if (number <= 1) {
            System.out.print(number);
            return;   // KICK OUT OF THE RECURSION
        }

        remainder = number %2; 
        printBinaryform(number >> 1);
        System.out.print(remainder);
    }
}

答案 1 :(得分:0)

您可以使用 Integer.toBinaryString()方法,如下所示,

int n = 100;
System.out.println(Integer.toBinaryString(n));

Integer.toBinaryString()将int作为参数并返回String,因此您还可以执行以下操作:

int n=100;
String s = Integer.toBinaryString(n);
System.out.println(s);