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;
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)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With