Kotlin Program to Convert Decimal to Binary (Using Recursion, Loop, Bitwise, and More)
Introduction
Kotlin is a modern, concise, and expressive programming language that works on Android and other platforms.
If you’re learning number systems or want to build conversion tools, knowing how to convert decimal to binary in Kotlin is very useful. Let's explore 6 different methods with beginner-friendly explanations.
Problem Statement
Write multiple Kotlin programs to convert a decimal number into binary using different methods like loops, recursion, bitwise operations, and built-in utilities.
Use Cases
-
Teaching number system conversions to students.
-
Developing utilities in Android apps.
-
Handling binary representations in compilers or interpreters.
-
Understanding core logic and recursion in Kotlin.
Method 1: Using While Loop and StringBuilder
// Program 1: Convert Decimal to Binary using While Loop
fun convertUsingLoop(number: Int): String {
if (number == 0) return "0"
var num = number
val binary = StringBuilder()
while (num > 0) {
binary.append(num % 2)
num /= 2
}
return binary.reverse().toString()
}
fun main() {
println("Binary (37): ${convertUsingLoop(37)}")
}
Easy Explanation
-
Use modulo
%
to get remainders. -
Append each bit to a StringBuilder.
-
Reverse the binary string at the end.
Output
Binary (37): 100101
Method 2: Using Recursion
// Program 2: Convert Decimal to Binary using Recursion
fun convertRecursive(number: Int): String {
if (number == 0) return ""
return convertRecursive(number / 2) + (number % 2)
}
fun main() {
val result = convertRecursive(19)
println("Binary (19): ${if (result.isEmpty()) "0" else result}")
}
Easy Explanation
-
Break the number using division.
-
Combine the result from smaller numbers recursively.
-
Append remainder at each return.
Output
Binary (19): 10011