3
所以,我需要你的幫助。我無法找到關於該主題的任何內容。 Golang是一種新鮮出爐的語言,因此很難爲像我這樣的新人找到答案。如何將int []轉換爲uint8 []
所以,我需要你的幫助。我無法找到關於該主題的任何內容。 Golang是一種新鮮出爐的語言,因此很難爲像我這樣的新人找到答案。如何將int []轉換爲uint8 []
預定義的Go int
類型大小是特定於實現的,或者是32位或64位(Numeric types)。
下面是將big-endian int
s轉換爲byte
s(uint8
s)的示例。
package main
import (
"encoding/binary"
"fmt"
"reflect"
)
func IntsToBytesBE(i []int) []byte {
intSize := int(reflect.TypeOf(i).Elem().Size())
b := make([]byte, intSize*len(i))
for n, s := range i {
switch intSize {
case 64/8:
binary.BigEndian.PutUint64(b[intSize*n:], uint64(s))
case 32/8:
binary.BigEndian.PutUint32(b[intSize*n:], uint32(s))
default:
panic("unreachable")
}
}
return b
}
func main() {
i := []int{0, 1, 2, 3}
fmt.Println("int size:", int(reflect.TypeOf(i[0]).Size()), "bytes")
fmt.Println("ints:", i)
fmt.Println("bytes:", IntsToBytesBE(i))
}
輸出:
int size: 4 bytes
ints: [0 1 2 3]
bytes: [0 0 0 0 0 0 0 1 0 0 0 2 0 0 0 3]
或
int size: 8 bytes
ints: [0 1 2 3]
bytes: [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 2 0 0 0 0 0 0 0 3]
我所期待的麻煩較少,例如(由於我的盲目相信Go有某種程序對這些類型的任務)。但是你的例子對我來說工作得很好,謝謝。 – oddy
應該注意的是,類型'int'不保證是32位。這是特定於實現的。目前的Go編譯器都擁有它,但是語言規範並沒有強制它,因此在將其轉換爲'uint32'時應該小心。有*可能*數據丟失。 – jimt
同樣值得注意的是,當使用顯式大小的整數時,可以編寫較少繁瑣的代碼。您可以使用binary.Write而不是在循環中調用binary.BigEndian.PutUint32。 –