More idiomatic way in Go to encode a []byte slice int an int64?

徘徊边缘 提交于 2019-12-03 12:28:05

You can use encoding/binary's ByteOrder to do this for 16, 32, 64 bit types

Play

package main

import "fmt"
import "encoding/binary"

func main() {
    var mySlice = []byte{244, 244, 244, 244, 244, 244, 244, 244}
    data := binary.BigEndian.Uint64(mySlice)
    fmt.Println(data)
}

It's almost overkill to use binary.BigEndian, since it's such a tiny amount of code, and there's some clarity gained by being able to see exactly what's going on. But this is a highly contentious opinion, so your own taste and judgement may differ.

func main() {
    var mySlice = []byte{123, 244, 244, 244, 244, 244, 244, 244}
    data := uint64(0)
    for _, b := range mySlice {
        data = (data << 8) | uint64(b)
    }
    fmt.Printf("%x\n", data)
}

I'm not sure about idiomatic, but here's an alternative using the encoding/binary package:

package main

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

func main() {
   var mySlice = []byte{244, 244, 244, 244, 244, 244, 244, 244}
   buf := bytes.NewReader(mySlice)
   var data int64
   err := binary.Read(buf, binary.LittleEndian, &data)
   if err != nil {
      fmt.Println("binary.Read failed:", err)
   }
   fmt.Println(data)
}

http://play.golang.org/p/MTyy5gIEp5

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!