Home > Article > Backend Development > How to Convert Go []byte to Little/Big-Endian Signed Integer or Floating-Point Numbers?
How to Convert Go []byte to Little/Big-Endian Signed Integer or Float?
When dealing with binary data, it's crucial to understand the concept of endianness, which refers to the way multi-byte numeric values are stored in memory. Go's binary package provides convenient functions for converting between big-endian and little-endian unsigned integer types like Uint16 and Uint32. However, it lacks direct support for signed integers and floating-point numbers.
The key to overcoming this limitation is to approach the task in two steps:
Converting to Signed Integers
To interpret a uint16 as a signed int16, for instance, simply use a type conversion, as they share the same memory layout:
<code class="go">a := binary.LittleEndian.Uint16(sampleA) a2 := int16(a)</code>
Similar principles apply for larger signed integer types like int64.
Converting to Floating-Point Numbers
While converting unsigned integers to floating-point types cannot be done directly through a type conversion, Go's math package provides functions specifically designed for this purpose. These functions allow you to convert unsigned integers to floats and vice versa without altering the underlying memory representation:
<code class="go">a := binary.LittleEndian.Uint64(sampleA) a2 := math.Float64frombits(a) // To convert back to unsigned integer: a3 := math.Float64bits(a2)</code>
Alternative Using binary.Read() and Write()
Go's binary.Read and Write functions can be used to perform these conversions more efficiently by accessing the underlying memory representation directly. Check out the example below:
<code class="go">pi := float64(3.141592653589793) buf := new(bytes.Buffer) binary.Write(buf, binary.LittleEndian, &pi) var result float64 binary.Read(buf, binary.LittleEndian, &result) fmt.Println(result)</code>
The above is the detailed content of How to Convert Go []byte to Little/Big-Endian Signed Integer or Floating-Point Numbers?. For more information, please follow other related articles on the PHP Chinese website!