Skip to content

Instantly share code, notes, and snippets.

@copyninja
Created March 11, 2014 09:14
Show Gist options
  • Save copyninja/9482168 to your computer and use it in GitHub Desktop.
Save copyninja/9482168 to your computer and use it in GitHub Desktop.
convert float to byte slice
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)
}
@copyninja
Copy link
Author

Output

11001101 11001100 100100 11000001 
-10.300000 

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment