我编写了一个将字节片转换为整数的函数。
我创建的函数实际上是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。这看起来确实很奇怪,但是它必须特定于平台,因为去游乐场报告的结果与我的机器(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
}
这是一个有根据的猜测,但是int
根据平台的不同,类型可以是64位或32位,在我的系统上是64位,因为操场在nacl上运行,所以是32位。
如果您将第二个函数更改为在各处都使用uint,它将可以正常工作。
从规格:
uint either 32 or 64 bits
int same size as uint
uintptr an unsigned integer large enough to store the uninterpreted bits of a pointer value
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句