Sling Academy
Home/Golang/Parsing Hexadecimal and Binary Input Strings in Go

Parsing Hexadecimal and Binary Input Strings in Go

Last updated: November 24, 2024

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.ParseInt to 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.FormatInt method 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.

Next Article: Using Bitwise Operations to Manipulate Binary Numbers in Go

Previous Article: Formatting Numbers for Output in Binary, Hex, and Decimal in Go

Series: Numbers and Math in Go

Golang

Related Articles

You May Also Like

  • How to remove HTML tags in a string in Go
  • How to remove special characters in a string in Go
  • How to remove consecutive whitespace in a string in Go
  • How to count words and characters in a string in Go
  • Relative imports in Go: Tutorial & Examples
  • How to run Python code with Go
  • How to generate slug from title in Go
  • How to create an XML sitemap in Go
  • How to redirect in Go (301, 302, etc)
  • Using Go with MongoDB: CRUD example
  • Auto deploy Go apps with CI/ CD and GitHub Actions
  • Fixing Go error: method redeclared with different receiver type
  • Fixing Go error: copy argument must have slice type
  • Fixing Go error: attempted to use nil slice
  • Fixing Go error: assignment to constant variable
  • Fixing Go error: cannot compare X (type Y) with Z (type W)
  • Fixing Go error: method has pointer receiver, not called with pointer
  • Fixing Go error: assignment mismatch: X variables but Y values
  • Fixing Go error: array index must be non-negative integer constant