Base64 is a widely used encoding scheme that represents binary data in an ASCII string format by translating it into a radix-64 representation. In Go, handling Base64 encoding and decoding is made simple by the encoding/base64 package. This article will guide you through the process of encoding and decoding numbers in Base64 in the Go programming language with an assortment of code examples.
Basic Base64 Encoding
To encode a number into Base64, we first need to convert the number to a byte slice (which is a slice of uint8) since Base64 encoding works with byte slices.
Example: Basic Base64 Encoding
package main
import (
"encoding/base64"
"fmt"
"strconv"
)
func main() {
num := 12345
// Convert the integer to a string
str := strconv.Itoa(num)
// Encode the string to base64
encoded := base64.StdEncoding.EncodeToString([]byte(str))
fmt.Println("Encoded:", encoded)
}
In this example, we convert the integer to a string, and then encode it using EncodeToString. The resulting string is the Base64 encoded representation of our number.
Intermediate Base64 Decoding
Decoding the Base64-encoded string back to its original number is a straightforward process.
Example: Base64 Decoding
package main
import (
"encoding/base64"
"fmt"
"strconv"
"log"
)
func main() {
encoded := "MTIzNDU="
// Decode from base64
decoded, err := base64.StdEncoding.DecodeString(encoded)
if err != nil {
log.Fatal(err)
}
// Convert back to integer
num, err := strconv.Atoi(string(decoded))
if err != nil {
log.Fatal(err)
}
fmt.Println("Decoded number:", num)
}
This code first decodes the Base64 string into the original string representing the number, and then converts it back to an integer using strconv.Atoi.
Advanced Base64 Usage: Custom Encoding
Sometimes, you might want to create a custom Base64 encoding. Go allows you to create and use a custom encoding using the NewEncoding function.
Example: Custom Base64 Encoding
package main
import (
"encoding/base64"
"fmt"
"strconv"
)
func main() {
customEncoding := base64.NewEncoding("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_")
num := 67890
// Convert the integer to a string
str := strconv.Itoa(num)
// Encode using custom base64
encoded := customEncoding.EncodeToString([]byte(str))
fmt.Println("Custom Encoded:", encoded)
}
This example demonstrates creating a custom Base64 encoding with a custom alphabet using NewEncoding. The rest of the process is similar to the standard encoding and decoding, allowing flexibility and experimentation with different sets of Base64 characters.
Conclusion
In this article, we've explored how to encode and decode numbers using Base64 in Go. By leveraging the encoding/base64 package, we can easily convert numbers to a Base64 representation and back. The examples included cover basic, intermediate, and advanced scenarios, providing a solid foundation in Base64 encoding mechanics in Go.