How to encode and decode data with variable-length encoding (e.g., varint) in Go?

In Go, you can encode and decode data with variable-length encoding, such as varint, using the encoding/binary package.

To encode an integer using varint encoding, you can use binary.Write function with a binary.VarintWriter:

package main import ( "encoding/binary" "fmt" "os" ) func main() { num := 150 // Encode the number using varint encoding buff := make([]byte, binary.MaxVarintLen64) n := binary.PutVarint(buff, int64(num)) // Write the encoded bytes to a file file, err := os.Create("encoded_data") if err != nil { fmt.Println("Error creating file:", err) return } defer file.Close() file.Write(buff[:n]) fmt.Println("Number encoded and written to file") }

To decode the encoded data back to the original integer, you can use binary.Read function with a binary.VarintReader:

package main import ( "encoding/binary" "fmt" "os" ) func main() { // Read the encoded varint bytes from file file, err := os.Open("encoded_data") if err != nil { fmt.Println("Error opening file:", err) return } defer file.Close() buff := make([]byte, binary.MaxVarintLen64) _, err = file.Read(buff) if err != nil { fmt.Println("Error reading file:", err) return } // Decode the varint bytes back to the original number num, bytesRead := binary.Varint(buff) if bytesRead <= 0 { fmt.Println("Error decoding varint") return } fmt.Println("Decoded number:", num) }

Make sure to change the file name in both code snippets to match the file where you want to read/write the encoded varint data.