📜  Java 十进制转换为二进制

📅  最后修改于: 2020-10-01 08:53:43             🧑  作者: Mango

#### Java十进制到二进制的转换：Integer.toBinaryString()

Integer.toBinaryString()方法将十进制转换为二进制字符串。 toBinaryString()方法的签名如下：

``````public static String toBinaryString(int decimal)
``````

``````public class DecimalToBinaryExample1{
public static void main(String args[]){
System.out.println(Integer.toBinaryString(10));
System.out.println(Integer.toBinaryString(21));
System.out.println(Integer.toBinaryString(31));
}}
``````

``````1010
10101
11111
``````

#### Java十进制到二进制的转换：自定义逻辑

``````public class DecimalToBinaryExample2{
public static void toBinary(int decimal){
int binary[] = new int[40];
int index = 0;
while(decimal > 0){
binary[index++] = decimal%2;
decimal = decimal/2;
}
for(int i = index-1;i >= 0;i--){
System.out.print(binary[i]);
}
System.out.println();//new line
}
public static void main(String args[]){
System.out.println("Decimal of 10 is: ");
toBinary(10);
System.out.println("Decimal of 21 is: ");
toBinary(21);
System.out.println("Decimal of 31 is: ");
toBinary(31);
}}
``````

``````Decimal of 10 is:
1010
Decimal of 21 is:
10101
Decimal of 31 is:
11111
``````