Parsing input strings is a common exercise in many programming scenarios, especially when working with data from different systems or user input that isn't directly an integer type. The Go programming language provides utilities to handle such conversions very effectively. In this article, we will explore how to parse hexadecimal and binary strings into integers and other numeric types in Go.
Basic Parsing of Hexadecimal Strings
Hexadecimal often represents binary in a more human-readable form. In Go, you can use the strconv package to parse hex strings. Here’s the simplest form:
package main
import (
"fmt"
"strconv"
)
func main() {
x, err := strconv.ParseInt("1a", 16, 64)
if err != nil {
fmt.Println("Error:", err)
return
}
fmt.Printf("Decimal: %d\n", x)
}
In the above example:
- We use
strconv.ParseIntto parse the hexadecimal string "1a". The second argument (16) specifies the base, for hexadecimal, and the third argument (64) specifies the bit size of the resulting integer. - If parsing is successful, it returns the integer. Otherwise, it provides an error.
Basic Parsing of Binary Strings
Binary strings need a similar approach but specifying base 2. Here is the basic way to parse binary strings:
package main
import (
"fmt"
"strconv"
)
func main() {
binary := "1011"
if val, err := strconv.ParseInt(binary, 2, 64); err == nil {
fmt.Printf("Decimal: %d\n", val)
} else {
fmt.Println("Error:", err)
}
}
In this example:
- The binary "1011" is parsed to an integer using base 2, with a bit size of 64.
Intermediate Parsing with Error Handling
For better error handling and more flexible code, you can separate parsing logic:
package main
import (
"fmt"
"strconv"
)
func parseHex(hexStr string) {
val, err := strconv.ParseInt(hexStr, 16, 64)
if err != nil {
fmt.Printf("Cannot parse %s: %v\n", hexStr, err)
return
}
fmt.Printf("Parsed Hex: %d\n", val)
}
func parseBinary(binStr string) {
val, err := strconv.ParseInt(binStr, 2, 64)
if err != nil {
fmt.Printf("Cannot parse %s: %v\n", binStr, err)
return
}
fmt.Printf("Parsed Binary: %d\n", val)
}
func main() {
parseHex("1a3f")
parseBinary("11101")
}
Advanced Parsing and Conversions
Sometimes, parsing is just part of a larger conversion task. For complex tasks, convert between different number systems:
package main
import (
"fmt"
"strconv"
)
func hexToBin(hexStr string) {
// Parse hex string to a numeric value
val, err := strconv.ParseInt(hexStr, 16, 64)
if err != nil {
fmt.Printf("Error while parsing hex: %v\n", err)
return
}
// Convert it back to a binary string.
binStr := strconv.FormatInt(val, 2)
fmt.Printf("Hex: %s is Binary: %s\n", hexStr, binStr)
}
func binToHex(binStr string) {
// Parse binary string to a numeric value
val, err := strconv.ParseInt(binStr, 2, 64)
if err != nil {
fmt.Printf("Error while parsing binary: %v\n", err)
return
}
// Convert it to a hex string.
hexStr := strconv.FormatInt(val, 16)
fmt.Printf("Binary: %s is Hex: %s\n", binStr, hexStr)
}
func main() {
hexToBin("afff")
binToHex("10111010100101")
}
This code demonstrates:
- Conversions from hex to binary and vice-versa.
- Handling of both base conversions using
strconv.FormatIntmethod to format the integer to different string representations.
This method is not only practical but also widely used in applications that require manipulation of data between different encodings and numeral systems. Understanding how Go’s strconv works will arm you with powerful tools for dealing with a wide range of data parsing tasks.