I am trying to unmarshal a data which is of type interface. So I need to convert the interface type to []byte and pass it to unmarshall. i tried
err := json.Unmarshal([]byte(kpi), &a) => failedkpidata, res := kpi.([]byte) => failed, kpidata is nilSo is there any way we can convert it?
我正在使用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))
}
Run Code Online (Sandbox Code Playgroud)
输出:
exp 65537
b: …Run Code Online (Sandbox Code Playgroud) 我正在编写一个小程序来使用 Go 检查字节序:
var i int = 0x0100
ptr := unsafe.Pointer(&i)
if 0x01 == *(*byte)(ptr) {
fmt.Println("Big Endian")
} else if 0x00 == *(*byte)(ptr) {
fmt.Println("Little Endian")
} else {
// ...
}
Run Code Online (Sandbox Code Playgroud)
我import "unsafe"打包转换*int为*byte. 但正如https://golang.org/pkg/unsafe/ 中提到的:
包 unsafe 包含绕过 Go 程序类型安全的操作。
导入不安全的包可能是不可移植的,不受 Go 1 兼容性指南的保护。
有没有更好的方法来确定字节序,还是我必须使用不安全的包?
我有以下字节数组:
buf := make([]byte, 1)
var value int8
value = 45
buf[0] = value // cannot use type int8 as type []byte in assignment
Run Code Online (Sandbox Code Playgroud)
当我想将一个char值放入字节数组时,我得到了错误cannot use type int8 as type []byte in assignment.怎么了?我该怎么做呢?