Q:

Kotlin program to convert octal number to binary number

belongs to collection: Kotlin Basic Programs

0

Given a number in octal number system format, we have to convert it into binary number system format.

Example:

    Input:
    num = 123

    Output:
    1010011

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Program to convert octal number to binary number in Kotlin

package com.includehelp.basic

import java.util.*

//Function to Convert Octal to Decimal
fun convertOctalToDecimal(_octalNumber:Long):Long{
    var octalNumber = _octalNumber
    var decimalNumber: Long=0
    var i = 0

    //Convert Octal to Decimal
    while (octalNumber > 0) {
        val r= octalNumber % 10
        decimalNumber += (r * Math.pow(8.0,i.toDouble())).toLong()
        octalNumber /= 10
        i ++
    }

    return decimalNumber;
}

/* function to convert given decimal into Binary */
fun convertDecimalToBinary(_decimalNumber: Long): Long {
    var decimalNum = _decimalNumber
    var binaryNum: Long = 0
    var i=1
    while (decimalNum > 0) {
        binaryNum += (decimalNum % 2 * i)
        decimalNum /= 2
        i *= 10
    }

    return binaryNum
}


//Function for Octal to Binary Number
fun octalToBinaryConversion(_octalNumber: Long): Long{
    //Call method to convert binary to decimal
    val decimal : Long = convertOctalToDecimal(_octalNumber)
    println("Decimal : $decimal")

    //Call method to convert decimal to binary
    val binary = convertDecimalToBinary(decimal);

    return binary
}

//Main function Entry Point of Program
fun main(arg: Array<String>) {
    var isCorrectOctal=true;

    //Input Stream
    val sc = Scanner(System.`in`)

    //Input Octal Number
    println("Enter Octal Number  : ")
    var octalNumber: Long = sc.nextLong()

    val octalStr = octalNumber.toString();
    //Check Given no is valid Octal Number or not
    for(i in octalStr.indices){
        if (octalStr[i] !in '0'..'7' ){
            isCorrectOctal=false
        }
    }

    if(isCorrectOctal){

        val binary = octalToBinaryConversion(octalNumber);

        //Print Binary
        println("Binary of Octal $octalNumber is : $binary")

    }else{
        System.err.println("Invalid Octal Number !!")
    }
}

Output

Run 1:
Enter Octal Number  :
23356549
Invalid Octal Number !!
-------
Run 2:
Enter Octal Number  :
123
Decimal : 83
Binary of Octal 123 is : 1010011
-------
Run 3:
Enter Octal Number  :
234
Decimal : 156
Binary of Octal 234 is : 10011100

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Kotlin Basic Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Kotlin program to convert octal number to decimal ... >>
<< Kotlin program to convert binary to decimal...