将`byte`数组转换为`uint32`数组

时间:2020-06-22 02:22:29

标签: go

我想将byte数组用作uint32数组,然后获取uint32数组的第一个元素。但是我无法使以下代码正常工作。有人可以让我知道如何将byte数组强制转换为unit32数组吗?谢谢。

// vim: set noexpandtab tabstop=2:

package main

import (
    "unsafe"
    "fmt"
)

func main() {
    x := []byte{'\x01', '\x02', '\x03', '\x04', '\x06', '\x07', '\x08', '\x09'}
    fmt.Printf("%#v\n", x)
    fmt.Printf("%#v\n", []int32(unsafe.Pointer(x))[0])
}

1 个答案:

答案 0 :(得分:0)

应该是

fmt.Printf("%#v\n", (*(*[]int32)(unsafe.Pointer(&x)))[0])

但是请记住,它仍然会有len = cap = 8(*),并仔细检查边界本身。

表达澄清

unsafe.Pointer(&x) // an uintptr to an `x` slice

(*[]int32)(...) // a type conversion
                // it's the same syntax when you do float64(42)
                // but in this case you need extra parentheses around the
                // type name to make it unambiguous for the parser
                // so, it converts a unitptr to a pointer to a int32 slice

*(...) // here it's just a pointer dereference. So you obtain a slice
       // from a pointer to a slice, to index it after

(*)cap在这种特殊情况下不能保证为8(但这并不重要)。