I have to convert hex
, represeneted as string
s (e.g. \"0xC40C5253\"
) to float values (IEEE-754 conversion). I did not manage
The input is 32 bits, so must be treated as a 32-bit number. It is also unsigned, so should be parsed as a uint, not int. Finally, there is no need to use unsafe operations, and in fact as used here they will fail on a machine with a different byte order.
Instead, use math.Float32frombits
, which does exactly what you want:
package main
import (
"fmt"
"math"
"strconv"
)
func main() {
s := "C40C5253"
n, err := strconv.ParseUint(s, 16, 32)
if err != nil {
panic(err)
}
nn := uint32(n)
g := math.Float32frombits(nn)
fmt.Println(g)
}
Output:
-561.2863
http://play.golang.org/p/y1ZjH9pscy