Reading and writing binary data
This recipe describes how to write and read any type in the binary form.
How to do it...
- Open the console and create the folder
chapter05/recipe07
. - Navigate to the directory.
- Create the
rwbinary.go
file with the following content:
package main import ( "bytes" "encoding/binary" "fmt" ) func main() { // Writing binary values buf := bytes.NewBuffer([]byte{}) if err := binary.Write(buf, binary.BigEndian, 1.004); err != nil { panic(err) } if err := binary.Write(buf, binary.BigEndian, []byte("Hello")); err != nil { panic(err) } // Reading the written values var num float64 if err := binary.Read(buf, binary.BigEndian, &num); err != nil { panic(err) } fmt.Printf("float64: %.3f\n", num) greeting := make([]byte...