dtr87341
2016-06-08 06:39
浏览 414
已采纳

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

}
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • douxiajia6104 2016-06-08 06:51
    已采纳

    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.

    打赏 评论
  • duanou2526 2016-06-09 15:52

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

    打赏 评论

相关推荐 更多相似问题