Posted on by Kalkicode
Code Conversion

Conversion from binary to octal in kotlin

Kotlin program for Conversion from binary to octal. Here mentioned other language solution.

//  Kotlin program for
//  Convert Binary number into Octal number
class Convert {
    // Convert decimal number into octal
    fun octal(num : Int) : Int
    {
      	var number : Int = num;
        var result : Int = 0;
        var multiplier : Int = 1;
        var remainder : Int ;
        while (number != 0)
        {
            remainder = number % 8;
            result = (remainder * multiplier) + result;
            multiplier *= 10;
            number = number / 8;
        }
        return result;
    }
    fun binaryToOctal(num : String) : Unit
    {
        if (num.length == 0)
        {
            // When empty binary number
            return;
        }
        // Some useful variable
        var flag : Boolean = false;
        var decimalNo : Int = 0;
        var counter : Int = 0;
        var index : Int = num.length - 1;
        // We Assume that given binary number is valid
        // Here - indicates negative binary number
        // First convert binary to decimal
        // Example = 10111 => 23
        while (index >= 0)
        {
            if (num.get(index) == '1')
            {
                decimalNo += (1 shl counter);
            }
            else
                if (num.get(index) != '0')
                {
                    if (index == 0 && num.get(index) == '-')
                    {
                        // When get negative number
                        flag = true;
                    }
                    else
                    {
                        // Not a valid binary number
                        return;
                    }
                }
            counter += 1;
            index -= 1;
        }
        // When given number is 
        var output : Int = this.octal(decimalNo);
        if (flag == true)
        {
            output = -output;
        }
        // Display given number
        print("Binary : " + num);
        // Display result
        println(" Octal : " + output);
    }
}
fun main(args : Array<String>) : Unit
    {
        val task : Convert = Convert();
        // Test Case
        task.binaryToOctal("1111");
        task.binaryToOctal("10111");
        task.binaryToOctal("101011");
        task.binaryToOctal("11011");
        task.binaryToOctal("-1000110");
    }

Output

Binary : 1111 Octal : 17
Binary : 10111 Octal : 27
Binary : 101011 Octal : 53
Binary : 11011 Octal : 33
Binary : -1000110 Octal : -106

Comment

Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment