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

后端 未结 3 1380
[愿得一人]
[愿得一人] 2021-02-15 03:16

Is there a better or more idiomatic way in Go to encode a []byte slice into an int64?

package main

import \"fmt\"

func main() {
    var mySlice = []byte{244, 2         


        
3条回答
  •  长情又很酷
    2021-02-15 03:39

    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

提交回复
热议问题