Hexadecimal (hex) numbers are base-16 numbers, which means they go from 0 to 9 and then A to F. In Go, the ability to manipulate these numbers is integral to several applications, from encoding to network programming. Let's look at how you can work with hexadecimal numbers in Go from basic conversions to more complex applications.
Basic Hexadecimal Representation
Let's start with the basics: how to represent a number in hexadecimal.
package main
import "fmt"
func main() {
hex := 0x1A
fmt.Printf("The number is: %d in decimal", hex)
}In this example, 0x1A represents the hexadecimal number 1A, which is 26 in decimal. Go allows you to specify a number as hexadecimal using the 0x or 0X prefix.
Decimal to Hexadecimal Conversion
Converting decimal numbers to hexadecimal is often necessary. Go provides the fmt package for formatting numbers.
package main
import "fmt"
func main() {
decimal := 42
hex := fmt.Sprintf("%x", decimal)
fmt.Println("Decimal to Hexadecimal:", hex)
}By using fmt.Sprintf("%x", decimal), the number 42 is converted to hexadecimal, which outputs "2a".
Hexadecimal to Decimal Conversion
For converting back from hexadecimal to decimal, you can use the Go standard library package strconv.
package main
import (
"fmt"
"strconv"
)
func main() {
hex := "2a"
decimal, err := strconv.ParseInt(hex, 16, 32)
if err != nil {
fmt.Println(err)
}
fmt.Println("Hexadecimal to Decimal:", decimal)
}In this script, strconv.ParseInt() converts the hexadecimal "2a" to a decimal value of 42.
Advanced - Working with Hexadecimal for Data Encoding
Hexadecimal is commonly used in data encoding. One application is converting byte slices to hexadecimal strings. Here's an example:
package main
import (
"fmt"
"encoding/hex"
)
func main() {
data := []byte("Golang")
hexString := hex.EncodeToString(data)
fmt.Println("String to Hex:", hexString)
}In this advanced example, the encoding/hex package's EncodeToString() function converts a byte slice to its hexadecimal string representation.
Advanced - Reading Hexadecimal Data
You may need to read hexadecimal data, such as a file hash or network data.
package main
import (
"fmt"
"encoding/hex"
)
func main() {
hexData := "476f6c616e67"
data, err := hex.DecodeString(hexData)
if err != nil {
fmt.Println(err)
}
fmt.Println("Decoded Hex to String:", string(data))
}Using DecodeString(), this code converts the hexadecimal string "476f6c616e67" back into the readable string "Golang".
This overview has introduced you to basic and advanced uses of hexadecimal numbers in Go. By understanding how to manipulate and interpret these numbers, round-tripping between different formats becomes straightforward.