How to encode and decode binary data in Go?

In Go, you can encode and decode binary data using the encoding/binary package. This package provides functions for performing both encoding and decoding operations on binary data.

  1. Import the encoding/binary package:
import "encoding/binary"
  1. To encode binary data, use the binary.Write() function:
var value uint32 = 42 data := make([]byte, 4) // Allocate a byte slice to hold the encoded value binary.LittleEndian.PutUint32(data, value) // Encode the value in little-endian byte order

The binary.Write() function writes the binary representation of the given value to the byte slice in the specified byte order. The PutUint32() function can be used to encode specific data types into a byte slice.

  1. To decode binary data, use the binary.Read() function:
var decodedValue uint32 binary.Read(bytes.NewReader(data), binary.LittleEndian, &decodedValue)

The binary.Read() function reads and decodes binary data from a byte slice or an io.Reader interface into the specified value. In this example, the value is read from a bytes.Reader initialized with the previously encoded data.

Note that you need to provide the byte order (binary.LittleEndian or binary.BigEndian) corresponding to the byte order used during encoding.

Here's the complete example of encoding and decoding binary data:

package main import ( "bytes" "encoding/binary" "fmt" ) func main() { var value uint32 = 42 // Encoding data := make([]byte, 4) binary.LittleEndian.PutUint32(data, value) fmt.Printf("Encoded data: %v\n", data) // Decoding var decodedValue uint32 binary.Read(bytes.NewReader(data), binary.LittleEndian, &decodedValue) fmt.Printf("Decoded value: %v\n", decodedValue) }

Output:

Encoded data: [42 0 0 0] Decoded value: 42

In this example, a uint32 value is encoded into a byte slice using little-endian byte order. Then, the encoded data is decoded back into a uint32 value. The encoded data and the decoded value are printed to the console.