A simple Go library for converting between decimal and binary numbers.
go get github.com/michaelwp/binaryConverterImport the package and use the BinaryConverter interface to convert between decimal and binary formats.
package main
import (
"fmt"
"github.com/michaelwp/binaryConverter"
)
func main() {
converter := binaryConverter.NewBinaryConverter()
// Convert decimal to binary
binary := converter.ToBinary(42)
fmt.Println("Binary of 42:", binary) // Output: "101010"
// Convert binary to decimal
decimal, err := converter.ToDecimal("101010")
if err != nil {
fmt.Println("Error:", err)
} else {
fmt.Println("Decimal of 101010:", decimal) // Output: 42
}
}Converts a decimal number to a binary string.
- Input:
int64 - Output:
string
Example:
converter.ToBinary(10) // Output: "1010"Converts a binary string to a decimal number.
- Input:
string(must be a valid binary representation) - Output:
int64, error
Example:
decimal, err := converter.ToDecimal("1010") // Output: 10, nilIf the input binary string is invalid, ToDecimal returns an error.
_, err := converter.ToDecimal("102")
if err != nil {
fmt.Println("Invalid binary string:", err)
}