英文:
More idiomatic way in Go to encode a []byte slice int an int64?
问题
在Go语言中,将[]byte切片编码为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
英文:
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, 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)
}
答案1
得分: 7
这是一小段代码,通过能够准确地看到正在发生的事情,可以获得一些清晰度。但这是一个非常有争议的观点,所以你自己的品味和判断可能会有所不同。
func main() {
var mySlice = []byte{244, 244, 244, 244, 244, 244, 244, 244}
data := int64(0)
for _, b := range mySlice {
data = (data << 8) | int64(b)
}
fmt.Printf("%d\n", data)
}
输出结果为:
-795741901218843404
Playground链接: https://go.dev/play/p/aemkEg7a6S5
英文:
It's such a tiny amount of code, 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{244, 244, 244, 244, 244, 244, 244, 244}
data := int64(0)
for _, b := range mySlice {
data = (data << 8) | int64(b)
}
fmt.Printf("%d\n", data)
}
Prints:
-795741901218843404
Playground: https://go.dev/play/p/aemkEg7a6S5
答案2
得分: 1
我不确定是否符合惯用语,但这里有一个使用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)
}
这里是一个可以运行的示例链接。
英文:
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)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论