doulvyi2172 2015-08-26 10:02
浏览 1823
已采纳

如何在golang中将uintptr转换为[] byte?

I don't know how to do it. It doesn't compile using []byte(uintptr(0)).

Please show me an example.

  • 写回答

2条回答 默认 最新

  • dq8081 2015-08-26 10:26
    关注

    That depends on what's your machine's architecture (32- or 64-bit) and how do you want it to be encoded (little- or big-endian). Either way, encoding/binary is your answer:

    var u uintptr = 42
    size := unsafe.Sizeof(u)
    b := make([]byte, size)
    switch size {
    case 4:
        binary.LittleEndian.PutUint32(b, uint32(u))
    case 8:
        binary.LittleEndian.PutUint64(b, uint64(u))
    default:
        panic(fmt.Sprintf("unknown uintptr size: %v", size))
    }
    

    Playground: http://play.golang.org/p/tIocqy-rAJ.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?