Convert between slices of different types

前端 未结 7 987
南旧
南旧 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:21

    You do what you do in C, with one exception - Go does not allow to convert from one pointer type to another. Well, it does, but you must use unsafe.Pointer to tell compiler that you are aware that all rules are broken and you know what you are doing. Here is an example:

    package main
    
    import (
        "fmt"
        "unsafe"
    )
    
    func main() {
        b := []byte{1, 0, 0, 0, 2, 0, 0, 0}
    
        // step by step
        pb := &b[0]         // to pointer to the first byte of b
        up := unsafe.Pointer(pb)    // to *special* unsafe.Pointer, it can be converted to any pointer
        pi := (*[2]uint32)(up)      // to pointer to the first uint32 of array of 2 uint32s
        i := (*pi)[:]           // creates slice to our array of 2 uint32s (optional step)
        fmt.Printf("b=%v i=%v\n", b, i)
    
        // all in one go
        p := (*[2]uint32)(unsafe.Pointer(&b[0]))
        fmt.Printf("b=%v p=%v\n", b, p)
    }
    

    Obviously, you should be careful about using "unsafe" package, because Go compiler is not holding your hand anymore - for example, you could write pi := (*[3]uint32)(up) here and compiler wouldn't complain, but you would be in trouble.

    Also, as other people pointed already, bytes of uint32 might be layout differently on different computers, so you should not assume these are layout as you need them to be.

    So safest approach would be to read your array of bytes one by one and make whatever you need out of them.

    Alex

提交回复
热议问题