-1

How could I convert the following byte array to uintptr? (not uint32 or uint64):

arr := []byte{0xda, 0xcc, 0xd9, 0x74, 0x24, 0xf4}
4
  • While this is close I need to convert to uintptr that example converts to uint. Commented Feb 1, 2020 at 0:57
  • Type cast: **(**uintptr)(unsafe.Pointer(&byte_slice)) Commented Feb 1, 2020 at 1:04
  • Btw uint has same size as uintptr, so it's well convertable uintptr(uint_variable) Commented Feb 1, 2020 at 1:06
  • Worth mentioning: you have six bytes in your slice, while pointers are probably either 4 or 8 bytes long. Probably you want 0x0000<hexvalue> for some six digit hex value, but it's not clear whether the final result should be 0x0000f42474d9ccda or 0x0000daccd97424f4. My first bet would be the latter (because 0xda is only 2-byte aligned) but it's still not really clear: if it is the latter, excising the first two 00 bytes is weird. Commented Feb 2, 2020 at 0:48

2 Answers 2

1

You can use encoding.binary package:

arr := []byte{0xda, 0xcc, 0xd9, 0x74, 0x24, 0xf4}

for i := 0; i < 8 - len(arr); i++ {
    arr = append([]byte{0x0, 0x0}, arr...) // for not to get index out of range
}
ptr := binary.BigEndian.Uint64(arr)
fmt.Printf("0x%x\n", uintptr(ptr))

https://play.golang.org/p/QFUVlIFdLZL

Sign up to request clarification or add additional context in comments.

Comments

1

Assuming that uintptr is 64-bits, and that you want a big-endian encoding, you can quite easily construct the right value even without delving into the standard library's binary package.

package main

import "fmt"

func main() {
    arr := []byte{0xda, 0xcc, 0xd9, 0x74, 0x24, 0xf4}
    var r uintptr
    for _, b := range arr {
        r = (r << 8) | uintptr(b)
    }
    fmt.Printf("%x", r)
}

This code outputs daccd97424f4 if you're on a 64-bit int version of go (and not, for example, on the go playground).

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.