Q:

Kotlin program to convert binary number to octal number

belongs to collection: Kotlin Basic Programs

0

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

Example:

    Input:
    num = 1001010111

    Output:
    1127

All Answers

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

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

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 binary to decimal... >>
<< Kotlin program to convert decimal number to octal ...