In Go, you can convert unsigned integers into a byte array using the Uint16() and Uint32() methods of the binary.BigEndian and binary.LittleEndian types. However, you may have noticed the absence of equivalent Int16() or Float32() methods.
Endianness refers to the order in which bytes are stored in memory for a given numeric type. Go's binary package provides functionality for converting between different endiannesses.
To convert an unsigned integer to a signed integer, you can use a simple type conversion. The memory layout of an unsigned 16-bit integer (uint16) and a signed 16-bit integer (int16) is the same. Therefore, you can perform the following conversion:
<code class="go">a := binary.LittleEndian.Uint16(sampleA) a2 := int16(a)</code>
This conversion does not change the memory representation, only the type.
Converting unsigned integers to floating-point numbers is slightly more involved. Go's math package provides functions for converting between unsigned integers and floats, such as math.Float32frombits() and math.Float64frombits().
<code class="go">a := binary.LittleEndian.Uint64(sampleA) a2 := math.Float64frombits(a)</code>
This conversion does not manipulate the memory value but instead "views" it as a different type using the unsafe package.
The binary package also provides Read() and Write() functions, which perform these conversions under the hood. You can use these functions to convert between different numeric types and byte arrays.
<code class="go">var pi float64 buf := bytes.NewReader(b) err := binary.Read(buf, binary.LittleEndian, &pi) // or a := binary.LittleEndian.Uint64(b) a2 := math.Float64frombits(a)</code>
In this example, the input byte array contains the value of pi in little-endian format. The Read() function converts the byte array into a float64 value, while Uint64() and Float64frombits() perform the conversion manually.
The above is the detailed content of How to Convert Numeric Types to []byte and Back in Go?. For more information, please follow other related articles on the PHP Chinese website!