Go Tutorials

Go Programs

Go Convert Decimal to Binary


Go Convert Decimal to Binary

In this tutorial, we will learn how to convert a decimal number to binary in Go. We will cover the basic concept of binary numbers and implement a function to perform the conversion.


What is Binary Conversion

Binary conversion is the process of converting a decimal (base-10) number to a binary (base-2) number. In binary, numbers are represented using only 0s and 1s.


Syntax

The syntax to convert a decimal number to binary in Go is:

func decimalToBinary(n int) string {
    if n == 0 {
        return "0"
    }
    binary := ""
    for n > 0 {
        remainder := n % 2
        binary = fmt.Sprintf("%d%s", remainder, binary)
        n = n / 2
    }
    return binary
}


Converting a decimal number to binary

We can create a function to convert a given decimal number to binary by repeatedly dividing the number by 2 and keeping track of the remainders.

For example,

  1. Define a function named decimalToBinary that takes one parameter n of type int.
  2. Check if n is 0. If true, return '0'.
  3. Initialize an empty string binary to store the binary representation.
  4. Use a for loop to repeatedly divide n by 2 and prepend the remainder to binary until n becomes 0.
  5. Return the binary representation as a string.
  6. In the main function, call the decimalToBinary function with a sample number and print the result.

Go Program

package main

import (
    "fmt"
)

func decimalToBinary(n int) string {
    if n == 0 {
        return "0"
    }
    binary := ""
    for n > 0 {
        remainder := n % 2
        binary = fmt.Sprintf("%d%s", remainder, binary)
        n = n / 2
    }
    return binary
}

func main() {
    // Convert 10 to binary
    result := decimalToBinary(10)

    // Print the result
    fmt.Printf("Binary representation of 10 is %s\n", result)
}

Output

Binary representation of 10 is 1010