I need to convert a slice of int64 to a byte array in golang. I am successfully able to do so for a single int64
var p int64 = -3984171602573983744
fmt.Println(p)
cn := make([]byte, 8)
binary.LittleEndian.PutUint64(cn, uint64(p))
fmt.Println(cn)
How can I implement it for a slice of int64?
To be more precise, I am trying to call a function in a library which writes to a DB, and that function takes a byte array as a param. I have a slice of int64 which I need to convert to a byte array and vice versa. Is this possible?
For each of the int64's loop and store it like binary.LittleEndian.PutUint64(cn[x:], yourUint64)
, where x
becomes 0,8,16...as you loop. Your cn
should be big enough to take all the data (it'll be some multiple of 8). When you want to read, do the reverse: x1 := binary.LittleEndian.Uint64(cn[n:n+8])
, where n
becomes 0, 1, 2..
See https://play.golang.org/p/YVQOAG8-Xlm for a simpler muxing-demuxing example.
For example,
package main
import (
"bytes"
"encoding/binary"
"fmt"
"math"
)
func main() {
w64 := []int64{math.MinInt64, -1, 0, 1, math.MaxInt64}
fmt.Println(w64)
// Write []int64 to database []byte
wbuf := new(bytes.Buffer)
err := binary.Write(wbuf, binary.LittleEndian, w64)
if err != nil {
fmt.Println("binary.Write failed:", err)
}
db := wbuf.Bytes()
fmt.Printf("% x
", db)
// Read database []byte to []int64
rbuf := bytes.NewBuffer(db)
r64 := make([]int64, (len(db)+7)/8)
err = binary.Read(rbuf, binary.LittleEndian, &r64)
if err != nil {
fmt.Println("binary.Read failed:", err)
}
fmt.Println(r64)
}
Playground: https://play.golang.org/p/4OscSOGZE52
Output:
[-9223372036854775808 -1 0 1 9223372036854775807]
00 00 00 00 00 00 00 80 ff ff ff ff ff ff ff ff 00 00 00 00 00 00 00 00 01 00 00 00 00 00 00 00 ff ff ff ff ff ff ff 7f
[-9223372036854775808 -1 0 1 9223372036854775807]