Converting Hexadecimal to IEEE-754 Float
To convert hexadecimal strings like "0xC40C5253" to IEEE-754 float values, the standard strconv.ParseFloat function is not sufficient. This article explores alternative methods to achieve this conversion.
First, determine the bit-length of the input. In this case, with 8 hex digits, it's likely a 32-bit float (though confirmation from the user is recommended).
Using strconv.ParseUint and Unsafe Conversion:
Code:
s := "C40C5253" n, err := strconv.ParseUint(s, 16, 32) if err != nil { panic(err) } n2 := uint32(n) f := *(*float32)(unsafe.Pointer(&n2))
Alternative Using math.Float32frombits:
The math package provides a built-in function Float32frombits() that directly converts a uint32 to a float32.
Code:
f := math.Float32frombits(n2)
Usage:
With either method, you can now access the float value stored in f. For example:
fmt.Println(f) // Output: -561.2863
The above is the detailed content of How to Convert Hexadecimal Strings to IEEE-754 Floats in Go?. For more information, please follow other related articles on the PHP Chinese website!