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
fmtpackage to handle input and output
operations, and thestrconvpackage for converting the decimal number to binary. - Function
decimalToBinary: This function takes an integer (decimal) as input
and usesstrconv.FormatIntto convert it to its binary equivalent. The result is returned
as a string. - In the
mainfunction: The program first asks the user to enter a decimal number
usingfmt.Scanto read the input. The entered decimal number is then passed to the
decimalToBinaryfunction, and the binary equivalent is printed usingfmt.Printf.
How to Run the Program
To run this program, follow these steps:
- Install Go on your machine. You can download it from Go’s official website.
- Create a new file with a .go extension, for example
decimal_to_binary.go. - Copy the above code into the file.
- Open a terminal or command prompt and navigate to the directory where the file is saved.
- Run the program by typing
go run decimal_to_binary.goand hit enter. - Enter a decimal number when prompted, and the program will output the corresponding binary equivalent.

