"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How can I convert byte arrays to signed integers and floats in Go?

How can I convert byte arrays to signed integers and floats in Go?

Published on 2024-11-07
Browse:403

How can I convert byte arrays to signed integers and floats in Go?

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:

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
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3