Go Program to Convert Binary Numbers to Decimal
This document explains a Go program designed to convert binary numbers to decimal. The program is structured to take a binary number as input and output its decimal equivalent.
Program Explanation
The Go program to convert a binary number to a decimal is divided into several sections:
- Package Declaration: The program starts with declaring the package name as
main
. - Importing Packages: We import necessary packages. In this case, we use the
fmt
package for input and output operations andstrconv
for string conversion operations. - Main Function: The main function is the entry point of the program where the conversion logic is implemented.
Go Code
package main
import (
"fmt"
"strconv"
)
// main is the entry point of the program
func main() {
// Prompt user for binary input
fmt.Print("Enter a binary number: ")
var binaryInput string
fmt.Scanln(&binaryInput)
// Convert binary to decimal
decimalOutput, err := binaryToDecimal(binaryInput)
if err != nil {
fmt.Println("Error:", err)
return
}
// Print the result
fmt.Printf("The decimal equivalent of %s is %d\n", binaryInput, decimalOutput)
}
// binaryToDecimal converts a binary string to a decimal integer
func binaryToDecimal(binaryStr string) (int64, error) {
// Parse the binary string using base 2
decimalValue, err := strconv.ParseInt(binaryStr, 2, 64)
if err != nil {
return 0, err
}
return decimalValue, nil
}
Program Details
Let’s go through the code in detail:
Package Declaration
package main
This line declares the package name. In Go, the main
package is used for executable commands.
Importing Packages
import (
"fmt"
"strconv"
)
Here, we import two packages: fmt
for formatting input and output, and strconv
for converting string data types.
Main Function
// main is the entry point of the program
func main() {
fmt.Print("Enter a binary number: ")
var binaryInput string
fmt.Scanln(&binaryInput)
decimalOutput, err := binaryToDecimal(binaryInput)
if err != nil {
fmt.Println("Error:", err)
return
}
fmt.Printf("The decimal equivalent of %s is %d\n", binaryInput, decimalOutput)
}
The main
function prompts the user to enter a binary number, reads the input, and then calls the binaryToDecimal
function to convert it. If the conversion is successful, it prints the decimal equivalent; otherwise, it prints an error message.
binaryToDecimal Function
// binaryToDecimal converts a binary string to a decimal integer
func binaryToDecimal(binaryStr string) (int64, error) {
decimalValue, err := strconv.ParseInt(binaryStr, 2, 64)
if err != nil {
return 0, err
}
return decimalValue, nil
}
This function takes a binary string as input and converts it to a decimal integer using the strconv.ParseInt
function with base 2. If the conversion is successful, it returns the decimal value; otherwise, it returns an error.