Go conversion between struct and byte array

后端 未结 4 1976
慢半拍i
慢半拍i 2021-01-02 13:41

I am writing a client - server application in Go. I want to perform C-like type casting in Go.

E.g. in Go

type packet struct {
    opcode uint16
             


        
4条回答
  •  無奈伤痛
    2021-01-02 14:26

    Thank you for answers and I am sure they work perfectly. But in my case I was more interested in parsing the []byte buffer received as network packet. I used following method to parse the buffer.

    var data []byte // holds the network packet received
    opcode := binary.BigEndian.Uint16(data) // this will get first 2 bytes to be interpreted as uint16 number
    raw_data := data[2:len(data)] // this will copy rest of the raw data in to raw_data byte stream
    

    While constructing a []byte stream from a struct, you can use following method

    type packet struct {
        opcode uint16
        blk_no uint16
        data   string
    }
    pkt := packet{opcode: 2, blk_no: 1, data: "testing"}
    var buf []byte = make([]byte, 50) // make sure the data string is less than 46 bytes
    offset := 0
    binary.BigEndian.PutUint16(buf[offset:], pkt.opcode)
    offset = offset + 2
    binary.BigEndian.PutUint16(buf[offset:], pkt.blk_no)
    offset = offset + 2
    bytes_copied := copy(buf[offset:], pkt.data)
    

    I hope this gives general idea about how to convert []byte stream to struct and struct back to []byte stream.

提交回复
热议问题