Kotlin Program to Convert Binary Number to Octal and Vice-Versa

Converting between binary and octal number systems is a common task in computing, especially in areas like computer memory addressing and digital electronics. In this article, you will learn how to implement a Kotlin program to convert binary numbers to octal and vice-versa. This article provides the detailed explanations and outputs for three real-world examples.

Binary (base-2) and octal (base-8) number systems are integral to computer science. Understanding how to convert between these systems can enhance your programming skills and comprehension of low-level computing processes. This article outlines the conversion methods and provides Kotlin code for both directions of conversion.

1. Binary to Octal Conversion

To convert a binary number to an octal number:

  1. Group the binary digits into sets of three, starting from the right. Add leading zeros if necessary.
  2. Convert each group of three binary digits to their octal equivalent.

Example:

Kotlin
fun binaryToOctal(binary: String): String {
    val binaryPadded = binary.padStart((binary.length + 2) / 3 * 3, '0')
    return binaryPadded.chunked(3).joinToString("") {
        it.toInt(2).toString(8)
    }
}

fun main() {
    val binary1 = "110101"
    val octal1 = binaryToOctal(binary1)
    println("Binary: $binary1 to Octal: $octal1")
}
Output
Kotlin
Binary: 110101 to Octal: 65
Explanation
  • Input: Binary: 110101
  • Pad binary: 110101
  • Grouped: 110 101
  • Octal equivalent: 6 5
  • Result: 65

2.Octal to Binary Conversion

To convert an octal number to a binary number:

  1. Convert each octal digit to its three-digit binary equivalent.
  2. Concatenate the binary groups to form the final binary number.

Example

Kotlin
fun octalToBinary(octal: String): String {
    return octal.map {
        it.toString().toInt(8).toString(2).padStart(3, '0')
    }.joinToString("")
}

fun main() {
    val octal2 = "65"
    val binary2 = octalToBinary(octal2)
    println("Octal: $octal2 to Binary: $binary2")
}
Output
Kotlin
Octal: 65 to Binary: 110101

Conclusion

This article demonstrated how to convert binary numbers to octal and vice-versa using Kotlin. We discussed the conversion logic, implemented the program, and provided real-world examples to illustrate the process. These conversions are crucial in various computing applications and understanding them can enhance your programming skills in Kotlin.

Feel free to experiment with the provided code and apply these concepts to your projects!