How to encode a slice as packed binary data and write to file

I have a slice
var slice []uint
slice = [1,2,3,4,5,6,7,8,9,10]

i want to encode this as packed binary data, slice to Binary.LittleEndian.PutUint32(byte, slice) does not work, and i want this to be a short uint(2 byte one) rather than the standard 4 byte uint. Cannot seem to find a method to do this. this packed binary data will be written to a file.

1 Like
package main

import (
	"encoding/binary"
	"fmt"
	"unsafe"
)

func main() {
	var slice []uint
	slice = []uint{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}

	// short uint(2 byte one)
	soUint16 := int(unsafe.Sizeof(uint16(0)))
	buf := make([]byte, soUint16*len(slice))
	for i, u := range slice {
		binary.LittleEndian.PutUint16(buf[soUint16*i:], uint16(u))
	}
	// write buf to file

	fmt.Printf("%d\n", buf)
}

https://play.golang.org/p/YH10WskUusP

1 Like

thank you :slight_smile:

what i ended up doing is(before reading your answer)

    data = make([]byte, 2)
    //from json , skipped the append to slice
    binary.LittleEndian.PutUint16(data, uint16(number.(float64)))
    _, err = f.Write(data)

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.