Decimal to Binary Converter in Go

 

Introduction

The process of converting a decimal number to binary is a common task in computer science and programming.
Decimal numbers (base-10) are the standard system for denoting integers, whereas binary (base-2) is the
language that computers use to process data. By converting a decimal number to binary, we are essentially
translating it into a format that is easier for computers to understand and process.

Objective

The objective of this program is to convert a given decimal number (base-10) to its binary equivalent
(base-2). This will help in understanding the basic conversion between number systems and how they are
handled by computers. The user will input a decimal number, and the program will output its binary form.

Code Implementation


package main

import (
    "fmt"
    "strconv"
)

func decimalToBinary(decimal int) string {
    return strconv.FormatInt(int64(decimal), 2)
}

func main() {
    var decimal int
    fmt.Print("Enter a decimal number: ")
    fmt.Scan(&decimal)

    binary := decimalToBinary(decimal)
    fmt.Printf("The binary equivalent of %d is: %s\n", decimal, binary)
}
            

Explanation of the Program

The program consists of the following key components:

  • Importing Packages: We import the fmt package to handle input and output
    operations, and the strconv package for converting the decimal number to binary.
  • Function decimalToBinary: This function takes an integer (decimal) as input
    and uses strconv.FormatInt to convert it to its binary equivalent. The result is returned
    as a string.
  • In the main function: The program first asks the user to enter a decimal number
    using fmt.Scan to read the input. The entered decimal number is then passed to the
    decimalToBinary function, and the binary equivalent is printed using fmt.Printf.

How to Run the Program

To run this program, follow these steps:

  1. Install Go on your machine. You can download it from Go’s official website.
  2. Create a new file with a .go extension, for example decimal_to_binary.go.
  3. Copy the above code into the file.
  4. Open a terminal or command prompt and navigate to the directory where the file is saved.
  5. Run the program by typing go run decimal_to_binary.go and hit enter.
  6. Enter a decimal number when prompted, and the program will output the corresponding binary equivalent.
© 2024 Learn Programming. All rights reserved.

 

One Reply to “Decimal to Binary Converter in Go”

Leave a Reply to binance Prihlásení Cancel reply

Your email address will not be published. Required fields are marked *