Given an octal number as input. Now, write a Kotlin program to convert Octal number to Binary.
1. Program to Convert Octal to Binary
Pseudo Algorithm
- Initialize a variable binaryNum with empty string.
- Now, convert each digit of octal number into binary and append it to binaryNum.
- Repeat till last digit of the octal number.
- Finally, binaryNum will contain binary representation of octal number.
Sourcecode –
if (checkOctalNumber(octalN!!)) { |
val octalNumString: String = octalN |
while (i < octalNumString.length) { |
when(octalNumString[i]) { |
'0' -> binaryNum += "000" |
'1' -> binaryNum += "001" |
'2' -> binaryNum += "010" |
'3' -> binaryNum += "011" |
'4' -> binaryNum += "100" |
'5' -> binaryNum += "101" |
'6' -> binaryNum += "110" |
'7' -> binaryNum += "111" |
println( "Equivalent Binary : $binaryNum" ) |
println( "$octalN is not an octal number" ) |
private fun checkOctalNumber(octalNum: String): Boolean { |
for (charAtPos in octalNum) { |
if (!((charAtPos >= '0' ) && (charAtPos <= '7' ))) { |
When you run the program, output will be –
Equivalent Binary : 111110101111101111110101111110101111101 |
Explanation:
We just extract each digit from the original octal number. Then, we converted that digit into binary and appended it with binaryNum
variable. Finally, binaryNum contains binary representation of the octal number.
Thus, we went through Kotlin Program to Convert Octal number to Binary number.