Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert uintptr to []byte in golang?

Tags:

go

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

Please show me an example.

like image 949
Kevin Gu Avatar asked Dec 10 '22 21:12

Kevin Gu


2 Answers

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.

like image 122
Ainar-G Avatar answered Jan 13 '23 07:01

Ainar-G


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

like image 36
Kevin Gu Avatar answered Jan 13 '23 07:01

Kevin Gu