我正在使用 big.NewInt(int64(e)).Bytes() 将 int32 转换为字节数组。有没有更优雅的方法来做到这一点?
我希望 AQAB 是 e 的 base64 编码值
http://play.golang.org/p/M46X7OpZpu
const e = 65537
func base64Encode(b []byte) string {
return strings.TrimRight(base64.StdEncoding.EncodeToString(b), "=")
}
func main() {
fmt.Printf("exp %d\n", e)
b := make([]byte, 4)
binary.BigEndian.PutUint32(b, e)
fmt.Printf("b: BigEndian.PutUint32 %x (Bad) %s\n", b, base64Encode(b))
b2 := make([]byte, 4)
binary.BigEndian.PutUint32(b2, e)
for i := range b2 {
if b2[i] != 0 {
b2 = b2[i:]
break
}
}
fmt.Printf("b2: BigEndian.PutUint32 %x (Good) %s\n", b2, base64Encode(b2))
b4 := big.NewInt(int64(e)).Bytes()
fmt.Printf("b4: big.NewInt(int64(e)).Bytes() %x (Good) %s\n", b4, base64Encode(b4))
}
输出:
exp 65537
b: BigEndian.PutUint32 00010001 (Bad) AAEAAQ
b2: BigEndian.PutUint32 010001 (Good) AQAB
b4: big.NewInt(int64(e)).Bytes() 010001 (Good) AQAB
exp 1
b: BigEndian.PutUint32 00000001 (Bad) AAAAAQ
b2: BigEndian.PutUint32 01 (Good) AQ
b4: big.NewInt(int64(e)).Bytes() 01 (Good) AQ
exp 1000000
b: BigEndian.PutUint32 000f4240 (Bad) AA9CQA
b2: BigEndian.PutUint32 0f4240 (Good) D0JA
b4: big.NewInt(int64(e)).Bytes() 0f4240 (Good) D0JA
编辑:
我已经对 b2 和 b4 进行了基准测试:
b2 1000000000 68.1 ns/op 8 B/op 1 allocs/op
b4 200000000 248 ns/op 90 B/op 3 allocs/op
我暂时用b2...