【发布时间】:2014-07-12 06:18:41
【问题描述】:
我写了一个函数来将字节切片转换为整数。
我创建的函数实际上是一个基于循环的实现 Rob Pike 在这里发表的内容:
http://commandcenter.blogspot.com/2012/04/byte-order-fallacy.html
这是 Rob 的代码:
i = (data[0]<<0) | (data[1]<<8) | (data[2]<<16) | (data[3]<<24);
我的第一个实现(操场上的 toInt2)不起作用 我期待,因为它似乎将 int 值初始化为 uint。 这看起来很奇怪,但它必须是特定于平台的,因为 go playground 报告的结果与我的机器(mac)不同。
谁能解释为什么这些函数在我的 mac 上表现不同?
这里是带有代码的游乐场的链接:http://play.golang.org/p/FObvS3W4UD
这是来自操场的代码(为方便起见):
/*
Output on my machine:
amd64 darwin go1.3 input: [255 255 255 255]
-1
4294967295
Output on the go playground:
amd64p32 nacl go1.3 input: [255 255 255 255]
-1
-1
*/
package main
import (
"fmt"
"runtime"
)
func main() {
input := []byte{255, 255, 255, 255}
fmt.Println(runtime.GOARCH, runtime.GOOS, runtime.Version(), "input:", input)
fmt.Println(toInt(input))
fmt.Println(toInt2(input))
}
func toInt(bytes []byte) int {
var value int32 = 0 // initialized with int32
for i, b := range bytes {
value |= int32(b) << uint(i*8)
}
return int(value) // converted to int
}
func toInt2(bytes []byte) int {
var value int = 0 // initialized with plain old int
for i, b := range bytes {
value |= int(b) << uint(i*8)
}
return value
}
【问题讨论】: