Jsmith
Jsmith

Reputation: 615

Convert one pointer to another type in golang

I want to convert a float64 number into int64 number. That is, I want to read the binary contents of the float64 register as if it is a int64 value. I mean, I want the go equivalent of the following C code

long y;
float x = 1.2;
y  = * ( long * ) &x;

How do I do that?

Here is my try which is not working.

package main

import (
    "fmt"
)

func main() {

    x := float64(1.2)
    y := *((*int64)(&x))

    fmt.Println("Ans:  ", y)

}

Upvotes: 2

Views: 6407

Answers (2)

jussius
jussius

Reputation: 3274

Go doesn't allow conversions between different types of pointers as it is inherently unsafe. But, if you still want to do it there is a Pointer type in unsafe package, which represents a pointer to an arbitrary type.

Any type of pointer can be converted to unsafe.Pointer and unsafe.Pointer can be converted to any type of pointer as long as they have the same memory structure. This allows you to ignore the type system and interpret any type of data as data of any other type.

The exact equivalent of the C code in your example in Go would be:

var y int64
var x float64 = 1.2
y = *(*int64)(unsafe.Pointer(&x))

So first we convert &x to unsafe.Pointer, then convert that to *int64 and finally dereference that to get an int64 with the same bit structure as x.

Remember that there is a reason this is in unsafe package. If you just want to know what the bits are, it's better to use math.Float64bits(). But if for example you must use bitwise operators on float then of course you have to convert it to int (and back).

Upvotes: 3

cnicutar
cnicutar

Reputation: 182619

That is, I want to read the binary contents of the float64 register as if it is a int64 value.

Try math.Float64bits:

x := float64(1.2)
fmt.Printf("Ans:  %x", math.Float64bits(x))

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

Prints Ans: 3ff3333333333333.

Upvotes: 5

Related Questions