Created
March 11, 2014 09:14
-
-
Save copyninja/9482168 to your computer and use it in GitHub Desktop.
convert float to byte slice
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"unsafe" | |
) | |
func main() { | |
var a = float32(-10.3) | |
var b = uintptr(unsafe.Pointer (&a)) | |
var c = make([]byte, unsafe.Sizeof(a)) | |
for i := 0; i < len(c); i ++ { | |
c[i] = byte(*((*byte)(unsafe.Pointer (b)))) | |
b = b + uintptr(1) | |
} | |
for i := 0; i < len(c); i++ { | |
fmt.Printf("%b ", c[i]) | |
} | |
fmt.Println() | |
var f = new(float32) | |
var fu = uintptr(unsafe.Pointer (f)) | |
for i := 0; i < len(c); i ++ { | |
*(*byte)(unsafe.Pointer(fu)) = c[i] | |
fu = fu + uintptr(1) | |
} | |
fmt.Printf("%f ", *f) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Output