'Convert []byte array to uintptr [duplicate]

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

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


Solution 1:[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

Solution 2:[2]

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).

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Paul Hankin