How to write binary data to a bufio.Writer in Go?

To write binary data to a bufio.Writer in Go, you can use the Write function with a []byte slice that contains the binary data.

Here's an example:

package main import ( "bufio" "encoding/binary" "fmt" "os" ) func main() { file, err := os.Create("binary_data.txt") if err != nil { fmt.Println(err) return } defer file.Close() writer := bufio.NewWriter(file) // Example binary data data := []int32{42, 1234, 5678} // Convert each integer to binary and write to the writer for _, num := range data { b := make([]byte, 4) binary.LittleEndian.PutUint32(b, uint32(num)) writer.Write(b) } writer.Flush() fmt.Println("Binary data written to file") }

In the above example, we are creating a new file called "binary_data.txt". We create a new bufio.Writer and use it to write the binary data.

The binary data, in this case, is an array of int32 values. For each int32 value, we use the binary.LittleEndian.PutUint32() function to convert it to a little-endian binary representation. We then write the resulting byte slice to the writer using the Write function.

Finally, we call Flush on the writer to ensure that any buffered data is written to the underlying file.

Note that in this example, we are using little-endian encoding with 4-byte integers, but you can adjust the size and encoding based on your specific requirements.