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

后端 未结 3 1378
[愿得一人]
[愿得一人] 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:58

    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)
    }
    

提交回复
热议问题