Converting Byte Arrays to Signed Integers and Floats in Go
In Go, the binary package offers functions for converting unsigned integers from []byte arrays, such as binary.LittleEndian.Uint16() and binary.BigEndian.Uint32(). However, there are no direct equivalents for signed integers or floats.
Reason for the Absence of Signed Integer Conversion Functions
The absence of signed integer conversion functions is primarily due to the fact that interpreting a binary representation as a signed or unsigned value is a matter of programming logic. The []byte array itself contains only raw binary data, which can be interpreted as either signed or unsigned depending on the application's requirements.
How to Convert to Signed Integers
To convert an unsigned integer value to a signed integer, a simple type conversion can be used. Since the memory layout of unsigned and signed integers of the same size is identical, converting a from uint16 to int16 using int16(a) will retain the original binary representation while assigning the appropriate sign.
Converting to Floats
Converting from unsigned integers to floats requires a bit more involvement. The math package provides functions for this purpose: math.Float32frombits() and math.Float64frombits(). Conversely, math.Float32bits() and math.Float64bits() can be used to obtain the unsigned integer representation of float values.
Use of Binary.Read() and Binary.Write()
The binary package also includes Read() and Write() functions that can perform these conversions more efficiently under the hood. These functions allow you to read directly into a typed value without the need for intermediate type conversions.
Example Using Binary.Read() for Float Conversion
Consider the following example:
<code class="go">b := []byte{0x18, 0x2d, 0x44, 0x54, 0xfb, 0x21, 0x09, 0x40} var pi float64 buf := bytes.NewReader(b) err := binary.Read(buf, binary.LittleEndian, &pi) if err != nil { fmt.Println("binary.Read failed:", err) } fmt.Println(pi) // Output: 3.141592653589793</code>
The above is the detailed content of How can I convert byte arrays to signed integers and floats in Go?. For more information, please follow other related articles on the PHP Chinese website!