Kotlin program to convert binary number to octal number

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

Kotlin - Convert binary number to octal number

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

Example:

Input:
num = 1001010111

Output:
1127

Program to convert binary number to octal number in Kotlin

package com.includehelp.basic

import java.util.*

// Function to check Valid Binary Number
fun isValidBinary(_binaryNumber: Long): Boolean {
    var binaryNumber = _binaryNumber
    while (binaryNumber > 0) {
        if (binaryNumber % 10 > 1) {
            return false
        }
        binaryNumber /= 10
    }
    return true
}

// Function to Convert Binary to Decimal
fun convertBinaryToDecimal(_binaryNumber: Long): Long {
    var binaryNumber = _binaryNumber
    var decimalNo : Long= 0
    var power = 0
    while (binaryNumber > 0) {
        val r = binaryNumber % 10
        decimalNo = (decimalNo + r * Math.pow(2.0, power.toDouble())).toLong()
        binaryNumber /= 10
        power++
    }
    return decimalNo
}

//function to convert binary to octal
fun binaryToOctalConversion(_binaryNum: Long): Long{

    //Call method to convert binary to decimal
    var decimal : Long = convertBinaryToDecimal(_binaryNum)
    println("Decimal : $decimal")

    var octalNumber: Long= 0
    var i = 1

    //Convert Decimal to Octal
    while (decimal > 0) {
        val r= decimal % 8
        octalNumber += r * i
        decimal /= 8
        i *= 10
    }

    return octalNumber
}

//Main function Entry Point of Program
fun main(arg: Array<String>) {

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

    //Input Binary Number
    println("Enter Binary Number  : ")
    var binaryNumber: Long = sc.nextLong()

    //check no. is valid binary or not
    if(isValidBinary(binaryNumber)){

        val octalNumber = binaryToOctalConversion(binaryNumber)
        //Print Octal Number
        println("Octal of binary $binaryNumber is : $octalNumber")

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

Output

Run 1:
Enter Binary Number  :
1001010111
Decimal : 599
Octal of binary 1001010111 is : 1127
-------
Run 2:
Enter Binary Number  :
10101010100101010
Decimal : 87338
Octal of binary 10101010100101010 is : 252452

Comments and Discussions!

Load comments ↻





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