简体   繁体   English

Go中更惯用的方式将[] byte slice编码为int64吗?

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

Is there a better or more idiomatic way in Go to encode a []byte slice into an int64? Go中有没有更好或更惯用的方式将[] byte slice编码为int64?

package main

import "fmt"

func main() {
    var mySlice = []byte{244, 244, 244, 244, 244, 244, 244, 244}
    var data int64
    for i := 0; i < 8; i++ {
                data |= int64(mySlice[i] & byte(255)) << uint((8*8)-((i+1)*8))
    }
    fmt.Println(data)
}

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

You can use encoding/binary's ByteOrder to do this for 16, 32, 64 bit types 您可以使用编码/二进制的ByteOrder16、32、64位类型执行此操作

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. 使用binary.BigEndian几乎是binary.BigEndian ,因为它的代码量非常小,而且能够准确地看到正在发生的事情,从而获得了一定的清晰度。 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: 我不确定惯用语言,但是这是使用encoding / binary包的替代方法:

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 http://play.golang.org/p/MTyy5gIEp5

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM