In Go, the encoding/binary package provides functionality for encoding and decoding binary data. This package is primarily used for converting data structures to and from binary streams. Using this package makes it convenient to handle binary data, such as reading data from binary files or writing data to binary files.
Using binary.Write() for Encoding
The binary.Write() function encodes data into binary format and writes it to an output stream. The function signature is as follows:
gofunc Write(w io.Writer, order ByteOrder, data interface{}) error
wis an object implementing theio.Writerinterface, such as a file or memory buffer.orderspecifies the byte order, commonlybinary.BigEndianorbinary.LittleEndian.datais the data to be encoded, typically a fixed-size value or a struct.
Example
Suppose we have a struct that we want to encode into binary data and write to a file:
gopackage main import ( "encoding/binary" "os" "log" ) type Example struct { ID int32 Flag bool } func main() { file, err := os.Create("example.bin") if err != nil { log.Fatal(err) } defer file.Close() data := Example{ID: 1024, Flag: true} // Using LittleEndian byte order err = binary.Write(file, binary.LittleEndian, data) if err != nil { log.Fatal(err) } }
Using binary.Read() for Decoding
The binary.Read() function reads binary data from an input stream and decodes it into a specified data structure. The function signature is as follows:
gofunc Read(r io.Reader, order ByteOrder, data interface{}) error
ris an object implementing theio.Readerinterface.orderspecifies the byte order, as mentioned above.datais a pointer to the data to be filled.
Example
Reading the previously written file and decoding into the struct:
gopackage main import ( "encoding/binary" "os" "log" ) type Example struct { ID int32 Flag bool } func main() { file, err := os.Open("example.bin") if err != nil { log.Fatal(err) } defer file.Close() var data Example // Using LittleEndian byte order err = binary.Read(file, binary.LittleEndian, &data) if err != nil { log.Fatal(err) } log.Printf("Read data: %+v", data) }
These examples demonstrate how to use the encoding/binary package for simple binary encoding and decoding tasks. This is very useful when interacting with hardware interfaces or network protocols.