Convert between slices of different types

前端 未结 7 962
南旧
南旧 2020-11-30 01:35

I get a byte slice ([]byte) from a UDP socket and want to treat it as an integer slice ([]int32) without changing the underlying array, and vice ve

7条回答
  •  迷失自我
    2020-11-30 02:19

    You can do it with the "unsafe" package

    package main
    
    import (
        "fmt"
        "unsafe"
    )
    
    func main() {
        var b [8]byte = [8]byte{1, 2, 3, 4, 5, 6, 7, 8}
        var s *[4]uint16 = (*[4]uint16)(unsafe.Pointer(&b))
        var i *[2]uint32 = (*[2]uint32)(unsafe.Pointer(&b))
        var l *uint64 = (*uint64)(unsafe.Pointer(&b))
    
        fmt.Println(b)
        fmt.Printf("%04x, %04x, %04x, %04x\n", s[0], s[1], s[2], s[3])
        fmt.Printf("%08x, %08x\n", i[0], i[1])
        fmt.Printf("%016x\n", *l)
    }
    
    /*
     * example run:
     * $ go run /tmp/test.go
     * [1 2 3 4 5 6 7 8]
     * 0201, 0403, 0605, 0807
     * 04030201, 08070605
     * 0807060504030201
     */
    

提交回复
热议问题