Home  >  Article  >  Backend Development  >  How do you convert Go []byte to Little/Big-Endian Signed Integer or Float?

How do you convert Go []byte to Little/Big-Endian Signed Integer or Float?

DDD
DDDOriginal
2024-10-31 01:15:03267browse

How do you convert Go []byte to Little/Big-Endian Signed Integer or Float?

Convert Go []byte to Little/Big-Endian Signed Integer or Float

Converting binary data stored in []byte to numeric types like signed integers or floating-point numbers requires an understanding of endianness. The endianness defines the order in which bytes are stored in memory, with two common formats being little-endian (least significant byte first) and big-endian (most significant byte first).

While the Go binary package provides functions like LittleEndian.Uint16() for converting []byte to unsigned integers, there are no direct equivalents for signed integers (Int16()). This is because endianness only affects the interpretation of the data, not its actual representation in memory.

To convert an unsigned integer to a signed integer, a simple type conversion is sufficient since they share the same memory layout. For example:

<code class="go">a := binary.LittleEndian.Uint16(sampleA)
a2 := int16(a)</code>

Similarly, you can convert an unsigned integer to a floating-point number using the math package functions Float32frombits() and Float64frombits().

<code class="go">a := binary.LittleEndian.Uint64(sampleA)
a2 := math.Float64frombits(a)</code>

The binary package also provides Read() and Write() functions that can perform these conversions under the hood.

<code class="go">import "bytes"

b := []byte{0x18, 0x2d, 0x44, 0x54, 0xfb, 0x21, 0x09, 0x40}

buf := bytes.NewReader(b)
var pi float64
err := binary.Read(buf, binary.LittleEndian, &amp;pi)
if err != nil {
    fmt.Println("binary.Read failed:", err)
}
fmt.Println(pi)

// Using Read() produces the same result as using Uint64() and Float64frombits():
a := binary.LittleEndian.Uint64(b)
a2 := math.Float64frombits(a)
fmt.Println(a2)

// Output:
// 3.141592653589793
// 3.141592653589793</code>

The above is the detailed content of How do you convert Go []byte to Little/Big-Endian Signed Integer or Float?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn