drlh197610 2015-12-03 23:01
浏览 49
已采纳

用Go编写打包二进制文件会产生与此Python相同输出的惯用方式是什么?

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)
  • 写回答

2条回答 默认 最新

  • dongyanju1094 2015-12-07 15:57
    关注

    After a little more tinkering and some feedback on another question I was able to come up with this (seems much cleaner but will post feedback on performance after testing with generating some large files):

    package main
    import (
            "os"
            "encoding/binary"
            )
    
    type binData struct {
        A int32
        B int32
        C int16
    }
    
    func main() {
            fp, err := os.Create("tst.bin")
    
            if err != nil {
                    panic(err)
            }
    
            defer fp.Close()
            bd := binData{A:4, B:185765, C:1020}
    
            binary.Write(fp, binary.LittleEndian, &bd)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用
  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?