Go Program to Convert Decimal to Binary (Using Bitwise Operator, Slice, Function, and Recursion)
Introduction
The binary number system forms the backbone of all computing systems. While humans prefer the decimal system (base 10)
, computers rely on binary (base 2)
.
In this tutorial, we will explore multiple ways to perform decimal to binary conversion in Go, covering different approaches like bitwise operations, slices, functions, and recursion.
Problem Statement
Write a Go program to convert a decimal number into binary using various methods: bitwise operations, slice manipulation, custom functions, and recursion.
Use Cases
-
Understanding binary representation in low-level programming.
-
Network addressing and subnet calculations.
-
Performing digital circuit simulations.
-
Embedded development in Go-based projects.
Method 1: Using Bitwise Operator
// Program 1: Convert Decimal to Binary using Bitwise Operator
package main
import (
"fmt"
)
func convertUsingBitwise(num int) string {
if num == 0 {
return "0"
}
binary := ""
started := false
for i := 31; i >= 0; i-- {
if (num>>i)&1 == 1 {
binary += "1"
started = true
} else if started {
binary += "0"
}
}
return binary
}
func main() {
num := 10
fmt.Println("Binary:", convertUsingBitwise(num))
}
Output
Binary: 1010
Method 2: Using Slice
// Program 2: Convert Decimal to Binary using Slice (Array-like)
package main
import (
"fmt"
)
func convertUsingSlice(num int) string {
if num == 0 {
return "0"
}
var binary []int
for num > 0 {
binary = append(binary, num%2)
num /= 2
}
// Reverse the slice
result := ""
for i := len(binary) - 1; i >= 0; i-- {
result += fmt.Sprintf("%d", binary[i])
}
return result
}
func main() {
num := 10
fmt.Println("Binary:", convertUsingSlice(num))
}
Explanation
-
Remainders are stored in a slice which mimics an array.
-
The slice is reversed to form the final binary string.
Method 3: Using Function (String Prepending)
// Program 3: Convert Decimal to Binary using a Simple Function
package main
import (
"fmt"
)
func convertToBinary(num int) string {
if num == 0 {
return "0"
}
result := ""
for num > 0 {
result = fmt.Sprintf("%d", num%2) + result
num /= 2
}
return result
}
func main() {
num := 10
fmt.Println("Binary:", convertToBinary(num))
}
Explanation
-
Binary is built by prepending bits to the string.
-
It avoids using slices or arrays and is quite concise.
Method 4: Using Recursion
// Program 4: Convert Decimal to Binary using Recursion
package main
import (
"fmt"
)
func convertRecursive(num int) string {
if num == 0 {
return ""
}
return convertRecursive(num/2) + fmt.Sprintf("%d", num%2)
}
func main() {
num := 10
binary := convertRecursive(num)
if binary == "" {
binary = "0"
}
fmt.Println("Binary:", binary)
}
Explanation
-
The recursive call divides the number and appends the bit during the return phase.
-
A base case checks for 0 to stop the recursion.