Kotlin program to convert octal number to binary number

Kotlin | Octal to Binary Conversion: Here, we are going to learn how to convert a given octal number to its equivalent binary number in Kotlin programming language? Submitted by IncludeHelp, on April 25, 2020

Kotlin - Convert octal number to binary number

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

Example:

Input:
num = 123

Output:
1010011

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

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.