dsdfd2322 2017-12-19 07:13
浏览 22
已采纳

序列化结构字段以预存现有的字节片

I have a setup where I receive data over the network and serialize it to my struct. It works fine, but now I need to serialize the data to a slice buffer to send it across the network.

I am trying to avoid having to allocate more than needed so I have already set up a buffer which I like to write to for all my serializing. But am not sure how to do this.

My setup is like this:

recieveBuffer := make([]byte, 1500)
header := recieveBuffer[0:1]
message := recieveBuffer[1:]

So I am trying to write fields from a struct to message and the total number of bytes for all the fields as a value for header.

This was how I deserialized to the struct:

// Deserialize ...
func (userSession *UserSession) Deserialize(message []byte) {
    userSession.UID = int64(binary.LittleEndian.Uint32(message[0:4]))
    userSession.UUID = string(message[4:40])
    userSession.Username = string(message[40:])
}

I don't really know how to do the reverse of this, however. Is it possible without creating buffers for each field I want to serialize before copying to message?

  • 写回答

2条回答 默认 最新

  • dongshi4078 2017-12-19 07:41
    关注

    Given the preallocated buffer buf, you can reverse the process like this:

    buf[0] = byte(40+len(userSession.Username))
    binary.LittleEndian.PutUint32(buf[1:], uint32(int32(userSession.UID)))
    copy(buf[5:41], userSession.UUID)
    copy(buf[41:], userSession.Username)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应