# Java 程序：十进制到二进制的转换

> 原文： [https://beginnersbook.com/2014/07/java-program-to-convert-decimal-to-binary/](https://beginnersbook.com/2014/07/java-program-to-convert-decimal-to-binary/)

将十进制数转换为二进制数有以下三种方法：

1）使用`Integer`类的[`toBinaryString()`方法](https://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html#toBinaryString(int))。

2）通过编写自己的逻辑进行转换，而无需使用任何预定义的方法。

3）使用`Stack`

### 方法 1：使用`toBinaryString()`方法

```java
class DecimalBinaryExample{

    public static void main(String a[]){
    	System.out.println("Binary representation of 124: ");
    	System.out.println(Integer.toBinaryString(124));
        System.out.println("\nBinary representation of 45: ");
        System.out.println(Integer.toBinaryString(45));
        System.out.println("\nBinary representation of 999: ");
        System.out.println(Integer.toBinaryString(999));
    }
}

```

**输出：**

```java
Binary representation of 124: 
1111100

Binary representation of 45: 
101101

Binary representation of 999: 
1111100111
```

### 方法 2：不使用预定义的方法

```java
class DecimalBinaryExample{

  public void convertBinary(int num){
     int binary[] = new int[40];
     int index = 0;
     while(num > 0){
       binary[index++] = num%2;
       num = num/2;
     }
     for(int i = index-1;i >= 0;i--){
       System.out.print(binary[i]);
     }
  }

  public static void main(String a[]){
     DecimalBinaryExample obj = new DecimalBinaryExample();
     System.out.println("Binary representation of 124: ");
     obj.convertBinary(124);
     System.out.println("\nBinary representation of 45: ");
     obj.convertBinary(45);
     System.out.println("\nBinary representation of 999: ");
     obj.convertBinary(999);
  }
}
```

**输出：**

```java
Binary representation of 124: 
1111100
Binary representation of 45: 
101101
Binary representation of 999: 
1111100111
```

### 方法 3：使用`Stack`进行二进制到十进制转换

```java
import java.util.*;
class DecimalBinaryStack
{
  public static void main(String[] args) 
  { 
    Scanner in = new Scanner(System.in);

    // Create Stack object
    Stack<Integer> stack = new Stack<Integer>();

    // User input 
    System.out.println("Enter decimal number: ");
    int num = in.nextInt();

    while (num != 0)
    {
      int d = num % 2;
      stack.push(d);
      num /= 2;
    } 

    System.out.print("\nBinary representation is:");
    while (!(stack.isEmpty() ))
    {
      System.out.print(stack.pop());
    }
    System.out.println();
  }
}
```

**输出：**

```java
Enter decimal number: 
999

Binary representation is:1111100111
```