I don't know how to do it.
It doesn't compile using []byte(uintptr(0))
.
Please show me an example.
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.
package main
import "fmt"
import "unsafe"
const sizeOfUintPtr = unsafe.Sizeof(uintptr(0))
func uintptrToBytes(u *uintptr) []byte {
return (*[sizeOfUintPtr]byte)(unsafe.Pointer(u))[:]
}
func main() {
var u = uintptr(1025)
fmt.Println(uintptrToBytes(&u))
}
http://play.golang.org/p/tIocqy-rAJ
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With