# Kotlin 程序：将二进制数转换为十进制，反之亦然

> 原文： [https://www.programiz.com/kotlin-programming/examples/binary-decimal-convert](https://www.programiz.com/kotlin-programming/examples/binary-decimal-convert)

#### 在此程序中，您将学习使用 Kotlin 中的函数将二进制数转换为十进制数，反之亦然。

访问此页面以了解[如何将二进制数转换为十进制](http://www.wikihow.com/Convert-from-Binary-to-Decimal "Binary number to Decimal")。

## 示例 1：将二进制数转换为十进制的程序

```kt
fun main(args: Array<String>) {
    val num: Long = 110110111
    val decimal = convertBinaryToDecimal(num)
    println("$num in binary = $decimal in decimal")
}

fun convertBinaryToDecimal(num: Long): Int {
    var num = num
    var decimalNumber = 0
    var i = 0
    var remainder: Long

    while (num.toInt() != 0) {
        remainder = num % 10
        num /= 10
        decimalNumber += (remainder * Math.pow(2.0, i.toDouble())).toInt()
        ++i
    }
    return decimalNumber
}
```

**输出**

```kt
110110111 in binary = 439 in decimal
```

* * *

访问此页面以了解[如何将十进制数转换为二进制](http://www.wikihow.com/Convert-from-Decimal-to-Binary "Binary number to Decimal")。

## 示例 2：将十进制数转换为二进制的程序

我们可以使用`Integer.toBinaryString()`方法将十进制数转换为二进制数。

```kt
fun main(args: Array<String>) {
    val num = 19

    // converting decimal to binary
    val binary = Integer.toBinaryString(num)
    println("$num in decimal = $binary in binary")
} 
```

* * *

这是将十进制数字手动转换为二进制的源代码。

## 示例 3：手动将十进制数转换为二进制

```kt
fun main(args: Array<String>) {
    val num = 19
    val binary = convertDecimalToBinary(num)
    println("$num in decimal = $binary in binary")
}

fun convertDecimalToBinary(n: Int): Long {
    var n = n
    var binaryNumber: Long = 0
    var remainder: Int
    var i = 1
    var step = 1

    while (n != 0) {
        remainder = n % 2
        System.out.printf("Step %d: %d/2, Remainder = %d, Quotient = %d\n", step++, n, remainder, n / 2)
        n /= 2
        binaryNumber += (remainder * i).toLong()
        i *= 10
    }
    return binaryNumber
}
```

运行该程序时，输出为：

```kt
Step 1: 19/2, Remainder = 1, Quotient = 9
Step 2: 9/2, Remainder = 1, Quotient = 4
Step 3: 4/2, Remainder = 0, Quotient = 2
Step 4: 2/2, Remainder = 0, Quotient = 1
Step 5: 1/2, Remainder = 1, Quotient = 0
19 in decimal = 10011 in binary
```

以下是等效的 Java 代码： [Java 程序：将二进制转换为十进制，反之亦然](/java-programming/examples/binary-decimal-convert "How to convert binary to decimal and vice-versa in Java")