In C language, you can convert 0.5
to 1056964608
in one shot.
#include <stdio.h>
int main() {
float f = 0.5;
printf("%d\n", *(int *)&f); // => 1056964608
}
(However, the writing method changes depending on the processing system and CPU architecture. The above is an example of MacOS Sierra and clang-900.0.39.2)
How can I write this in Go language? In conclusion, you can do something similar with the type ʻunsafe.Pointer`.
package main
import "fmt"
import "unsafe"
func main() {
var f float32 = 0.5
var p unsafe.Pointer
p = unsafe.Pointer(&f)
fmt.Printf("%d\n", *(*int32)(p)); // => 1056964608
}
What is useful is that it makes me feel like I'm messing with memory directly.
Recommended Posts