I'm trying to figure out how the best way to write a binary file in Go that corresponds with the following Python:
import struct
f = open('tst.bin', 'wb')
fmt = 'iih'
f.write(struct.pack(fmt,4, 185765, 1020))
f.close()
I have been tinkering with some of the examples I've seen on Github.com and a few other sources but I can't seem to get anything working correctly. What is the idiomatic way to do this sort of thing in Go?
Here is how I am accomplishing this now (Golang):
package main
import (
"fmt"
"os"
"encoding/binary"
)
func main() {
fp, err := os.Create("tst.bin")
if err != nil {
panic(err)
}
defer fp.Close()
aBuf := make([]byte, 4)
bBuf := make([]byte, 4)
cBuf := make([]byte, 2)
binary.LittleEndian.PutUint32(aBuf, 4)
binary.LittleEndian.PutUint32(bBuf, 185765)
binary.LittleEndian.PutUint16(cBuf, 1020)
binary.Write(fp, binary.LittleEndian, aBuf)
binary.Write(fp, binary.LittleEndian, bBuf)
binary.Write(fp, binary.LittleEndian, cBuf)
}
Verified with this Python:
import numpy as np
data = np.fromfile('tst.bin', dtype='i4,i4,i2')
print(data)