Skip to content

Instantly share code, notes, and snippets.

@helinwang
Last active February 6, 2023 02:29
Show Gist options
  • Save helinwang/9df4257e1f207bd3375524b0b84506d3 to your computer and use it in GitHub Desktop.
Save helinwang/9df4257e1f207bd3375524b0b84506d3 to your computer and use it in GitHub Desktop.
Go byte slice to float32 slice
package main
import (
"fmt"
"unsafe"
)
func byteSliceToFloat32Slice(src []byte) []float32 {
if len(src) == 0 {
return nil
}
l := len(src) / 4
ptr := unsafe.Pointer(&src[0])
// It is important to keep in mind that the Go garbage collector
// will not interact with this data, and that if src if freed,
// the behavior of any Go code using the slice is nondeterministic.
// Reference: https://github.com/golang/go/wiki/cgo#turning-c-arrays-into-go-slices
return (*[1 << 26]float32)((*[1 << 26]float32)(ptr))[:l:l]
}
func main() {
a := []byte{0, 0, 0, 0, 1, 1, 1, 1}
fmt.Println(byteSliceToFloat32Slice(a))
// Output: [0 2.3694278e-38]
}
@MatejMagat305
Copy link

please I need to float64

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