Last active
February 6, 2023 02:29
-
-
Save helinwang/9df4257e1f207bd3375524b0b84506d3 to your computer and use it in GitHub Desktop.
Go byte slice to float32 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 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] | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
please I need to float64