Kotlin Program to Convert Octal Number to Binary

Greetings!
We have recently published 100+ articles on android tutorials with kotlin and java. If you need, you may visit Android Tutorial for beginners page. You can also check Kotlin Tutorial for beginners. Also, if you are interested in content writing, you can mail us at tutorialwing@gmail.com.

Given an octal number as input. Now, write a Kotlin program to convert Octal number to Binary.

Input:
7

Output:
111
Input:
120

Output:
001010000
Input:
121

Output:
001010001

1. Program to Convert Octal to Binary

Pseudo Algorithm
  • Initialize a variable binaryNum with empty string.
  • Now, convert each digit of octal number into binary and append it to binaryNum.
  • Repeat till last digit of the octal number.
  • Finally, binaryNum will contain binary representation of octal number.

Sourcecode –

fun main() {

    println("Enter n:")
    val octalN = readLine()

    if(checkOctalNumber(octalN!!)) {
        val octalNumString: String = octalN

        var i = 0
        var binaryNum = ""
        while(i < octalNumString.length) {
            when(octalNumString[i]) {
                '0'  -> binaryNum += "000"
                '1'  -> binaryNum += "001"
                '2'  -> binaryNum += "010"
                '3'  -> binaryNum += "011"
                '4'  -> binaryNum += "100"
                '5'  -> binaryNum += "101"
                '6'  -> binaryNum += "110"
                '7'  -> binaryNum += "111"
            }
            i++
        }
        println("Equivalent Binary : $binaryNum")
    } else {
        println("$octalN is not an octal number")
    }
}

private fun checkOctalNumber(octalNum: String): Boolean {
    var isOctal = true

    for(charAtPos in octalNum) {
        if(!((charAtPos >= '0') && (charAtPos <= '7'))) {
            isOctal = false
            break
        }
    }
    return isOctal
}

When you run the program, output will be –

Enter n:
7657576576575
Equivalent Binary : 111110101111101111110101111110101111101
Explanation:

We just extract each digit from the original octal number. Then, we converted that digit into binary and appended it with binaryNum
variable. Finally, binaryNum contains binary representation of the octal number.

Thus, we went through Kotlin Program to Convert Octal number to Binary number.

Support Us

If you like Tutorialwing and would like to contribute, you can email an article on any educational topic at tutorialwing@gmail.com. We would love to publish your article. See your article on Tutorialwing and help others with your knowledge. Follow Facebook, LinkedIn, Google+, Twitter, Youtube for latest updates.
Greetings!
We have recently published 100+ articles on android tutorials with kotlin and java. If you need, you may visit Android Tutorial for beginners page. You can also check Kotlin Tutorial for beginners