-1

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

arr := []byte{0xda, 0xcc, 0xd9, 0x74, 0x24, 0xf4}
  • While this is close I need to convert to uintptr that example converts to uint. – user12822412 Feb 01 '20 at 00:57
  • Type cast: `**(**uintptr)(unsafe.Pointer(&byte_slice)) ` – Laevus Dexter Feb 01 '20 at 01:04
  • Btw uint has same size as uintptr, so it's well convertable `uintptr(uint_variable)` – Laevus Dexter Feb 01 '20 at 01:06
  • Worth mentioning: you have six bytes in your slice, while pointers are probably either 4 or 8 bytes long. Probably you want 0x0000 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. – torek Feb 02 '20 at 00:48

2 Answers2

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

Axifive
  • 1,159
  • 2
  • 19
  • 31
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).

Paul Hankin
  • 54,811
  • 11
  • 92
  • 118