#Packing data to struct.

5 messages · Page 1 of 1 (latest)

regal orbit
#

I am trying to pack some data to struct like python but not sure how approach it. it has multiple different type of data.

>>> z = [1,2 , b"hello"]
>>> f = "<i b 5s"
>>> p = struct.pack(f,*z)
>>> p
b'\x01\x00\x00\x00\x02hello'
>>>

I can do like this for python. I want to do something similar in go

here in format f , <i is little E int , b is signed char , 5s is []char with 5 size

lost robin
# regal orbit I am trying to pack some data to struct like python but not sure how approach it...

First []rune isn't what your encoded data looks like up to go, I guess you meant it should be utf8 encoded.

Also it's kinda slow, I would add a byte length prefix before the utf8.
It's more manual, but tldr you just do it:

var _ encoding.BinaryMarshaler = typ{}
type typ struct{
  a int32
  b int8
  c [5]rune
}

func (t typ) MarshalBinary() (data []byte, err error) {
  size := 4 + 1
  for _, r := range t.c {
    size += utf8.RuneLen(r)
  }

  data = make([]byte, size)
  binary.LittleEndian.PutUint32(data, t.a)
  data = data[4:]

  data[0] = t.b
  data = data[1:]

  for _, r := range t.c {
    runeSize := utf8.EncodeRune(data, r)
    data = data[runeSine:]
  }

  return data, nil
}
#

I wouldn't use this format or this struct to begin with tho

#

but that how you would do it

regal orbit
# lost robin First `[]rune` isn't what your encoded data looks like up to go, I guess you mea...

I got some idea from this solution, the python answer is equiv to

>>> z = [1,b"2" , b"hello"]
>>> f = "<ic5s"
>>> p = struct.pack(f,*z)
>>> p
b'\x01\x00\x00\x002hello'
>>> list(p)
[1, 0, 0, 0, 50, 104, 101, 108, 108, 111]

and if i do

var x bytes.Buffer
x.WriteByte(1)
x.WriteRune('2')
x.WriteString("hello")
fmt.Println(x.Bytes())

the answer is
[1 50 104 101 108 108 111]

so looks like buffer will work for now for me. thanks for the help