Scala Decimal to Binary Conversion – Loop, Recursion, Bitwise & Built-in
Objective
This guide explores how to convert a decimal number to binary in Scala, using different programming techniques like recursion, loops, bitwise operators, and built-in functions.
Scala’s powerful syntax makes each approach clean and expressive.
Real-World Use
-
Building backend logic for custom calculators or code compilers.
-
Educational tools that visualize number system conversions.
-
Practicing functional and recursive programming patterns in Scala.
Binary Conversion Using While Loop
// Convert decimal to binary using a while loop
def decimalToBinaryLoop(num: Int): String = {
if (num == 0) return "0"
var number = num
var binary = ""
while (number > 0) {
binary = (number % 2).toString + binary
number = number / 2
}
binary
}
println("Binary of 26: " + decimalToBinaryLoop(26))
Easy Steps
-
Use modulo to get the remainder (bit).
-
Prepend it to the binary result string.
-
Divide by
2
until the number becomes0
.
Output
Binary of 26: 11010
Recursive Binary Conversion
// Recursive method for decimal to binary conversion
def decimalToBinaryRecursive(num: Int): String = {
if (num == 0) ""
else decimalToBinaryRecursive(num / 2) + (num % 2).toString
}
val binaryValue = decimalToBinaryRecursive(31)
println("Binary of 31: " + (if (binaryValue == "") "0" else binaryValue))
Easy Steps
-
Keep dividing the number by 2 recursively.
-
On each return step, append the bit
(num % 2)
. -
Handle the base case by returning an empty string for
0
.
Output
Binary of 31: 11111
Using Bitwise Operators
// Convert decimal to binary using bitwise shifts
def decimalToBinaryBitwise(num: Int): String = {
var result = ""
var started = false
for (i <- 31 to 0 by -1) {
val bit = (num >> i) & 1
if (bit == 1) started = true
if (started) result += bit.toString
}
if (result.isEmpty) "0" else result
}
println("Binary of 20: " + decimalToBinaryBitwise(20))
Easy Steps
-
Shift the number right from the 31st bit.
-
Use bitwise
AND
&
to get current bit.1
-
Skip leading zeros by checking if
bit == 1
.
Output
Binary of 20: 10100
Using Built-in Integer Method
// Built-in conversion using Scala’s toBinaryString
val num = 14
println(s"Binary of $num: " + num.toBinaryString)
Easy Steps
-
Scala has a direct method
toBinaryString
. -
This prints the binary representation without any manual logic.
Output
Binary of 14: 1110
Wrap-up
This article presented four powerful Scala methods for decimal to binary conversion. You saw how to implement the logic manually using loop, recursion, bitwise operators, and how to use Scala’s built-in method for quick results.