Sling Academy
Home/Golang/Converting Integers to Hex Strings and Vice Versa in Go

Converting Integers to Hex Strings and Vice Versa in Go

Last updated: November 24, 2024

Introduction

In the Go programming language, converting integers to hexadecimal strings and vice versa is a common task, especially when dealing with binary data, debugging, or programming tasks that involve low-level data manipulation. In this article, we will explore how to efficiently perform these conversions in Go using its standard library, while providing code examples from basic to advanced levels.

Converting Integers to Hex Strings

Go provides a straightforward way to convert integers to hexadecimal strings using the strconv and fmt packages. Let’s look at some examples:

Basic Conversion

package main

import (
    "fmt"
)

func main() {
    number := 255
    hexString := fmt.Sprintf("%x", number) // Convert integer to hex
    fmt.Println("Hexadecimal representation:", hexString) // Output: ff
}

In this basic example, fmt.Sprintf("%x", number) is used to obtain a hexadecimal representation of the integer.

Intermediate: Converting with Uppercase Hex

package main

import (
    "fmt"
)

func main() {
    number := 255
    hexString := fmt.Sprintf("%X", number) // Convert integer to upper case hex
    fmt.Println("Uppercase Hexadecimal representation:", hexString) // Output: FF
}

The %X verb in Sprintf converts the number to an uppercase hexadecimal string.

Advanced: Custom Padding and Formatting

package main

import (
    "fmt"
)

func main() {
    number := 26
    hexString := fmt.Sprintf("%#04x", number) // Convert integer with 0x prefix, padded to four characters
    fmt.Println("Padded and formatted Hexadecimal representation:", hexString) // Output: 0x1a
}

In this advanced example, the format verb %#04x adds a 0x prefix and ensures the string is at least 4 characters long, padding with zeros if necessary.

Converting Hex Strings to Integers

To convert a hexadecimal string back to an integer, you can use the strconv package:

Basic Conversion

package main

import (
    "fmt"
    "strconv"
)

func main() {
    hexString := "ff"
    number, err := strconv.ParseInt(hexString, 16, 0) // Parse as base 16
    if err != nil {
        fmt.Println("Error parsing hex string:", err)
        return
    }
    fmt.Println("Parsed integer:", number) // Output: 255
}

Here, strconv.ParseInt is used to convert a hexadecimal string into an integer specifying base 16.

Intermediate: Handling Errors

package main

import (
    "fmt"
    "strconv"
)

func main() {
    hexString := "XYZ"
    number, err := strconv.ParseInt(hexString, 16, 0)
    if err != nil {
        fmt.Println("Invalid hex string:", err)
        return
    }
    fmt.Println("Parsed integer:", number)
}

This example demonstrates error handling when the hex string is not valid.

Advanced: Parsing Different Widths

package main

import (
    "fmt"
    "strconv"
)

func main() {
    hexString := "FFFFFFFF"
    number, err := strconv.ParseUint(hexString, 16, 32) // Parse as 32-bit unsigned integer
    if err != nil {
        fmt.Println("Error parsing hex string:", err)
        return
    }
    fmt.Println("Parsed 32-bit unsigned integer:", number) // Output: 4294967295
}

You can specify different bit widths for the parsing operation. Here ParseUint is used for an unsigned integer parsing as it can handle the full unsigned range for the given bit size.

Conclusion

In this article, we've covered various methods for converting integers to hexadecimal strings and vice versa in Go, with examples increasing in complexity. Understanding these operations can aid in many programming tasks from string formatting in output to conversions necessary for network programming and cryptographic utilities. By leveraging Go’s standard library functions, these conversions can be performed efficiently and effectively.

Next Article: Encoding and Decoding Binary Numbers in Go

Previous Article: Working with Hexadecimal Numbers 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