Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I convert pointer type in golang

Tags:

go

I want convert something like (*float32) to (*int32)

I do this

var f float32 = 0.0
var p *int32 = (*int32)(&f) // error!
// cannot convert &f (type *float32) to type *int32

How can I do this like what I'm done in C

float f = 0.0;
int *ip = (*int) &fp;
like image 901
Kiochan Avatar asked Dec 19 '16 10:12

Kiochan


1 Answers

You absolutely can do this in Go. There are two ways. One safe and one unsafe:

package main

import (
    "encoding/binary"
    "fmt"
    "math"
    "unsafe"
)

func main() {
    var f float32
    var i int32

    // unsafe
    f = 1.234
    i = *((*int32)(unsafe.Pointer(&f)))
    fmt.Println(f, i)

    // safe
    var tmp [4]byte
    f = 1.234
    binary.LittleEndian.PutUint32(tmp[:], math.Float32bits(f))
    i = int32(binary.LittleEndian.Uint32(tmp[:]))
    fmt.Println(f, i)
}
like image 95
Caleb Avatar answered Sep 19 '22 12:09

Caleb