Convert 8 byte array to int64?

6,964 views
Skip to first unread message

cthom lists

unread,
Mar 12, 2010, 9:29:17 AM3/12/10
to golan...@googlegroups.com
This is the solution I've come up with...

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

type Byte64 [8]byte

func (bits *Byte64) Read(p []byte) (r int, e os.Error) {
        if len(p) > 8 {
                e = os.EOF
        }
        for r = 0; r < 8 && r < len(p); r++ {
                p[r] = bits[r]
        }
        return
}

func main() {
        var n int64
        bits := new(Byte64)
        bits[0] = 1
        bits[1] = 2
        binary.Read(bits, binary.LittleEndian, &n)
        fmt.Printf("%d\n", n) //513
}

Is there an easier way to convert byte arrays to ints, etc?

Message has been deleted

peterGo

unread,
Mar 12, 2010, 1:27:43 PM3/12/10
to golang-nuts
cthom,

You could be more concise.

package main

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

func main() {
var n int64

b := [8]byte{1, 2}
buf := bytes.NewBuffer(&b)
binary.Read(buf, binary.LittleEndian, &n)
fmt.Println(n, b)
}


Peter

Ostsol

unread,
Mar 12, 2010, 8:21:11 PM3/12/10
to golang-nuts
For integer types you could alway just pack the bytes using
bitshifting.

-Daniel

Reply all
Reply to author
Forward
0 new messages