英文:
Send float32 values over udp socket
问题
我正在进行一个Go项目,我想使用UDPSocket发送float32值。
我不明白的是,在发送之前,将这些数字转换为字节缓冲区的最佳方法是什么,以及如何在接收后将它们转换回float32。
目前,我正在使用以下在网上找到的函数将float32->[]byte进行转换,但我甚至不确定我是否得到了我想要的结果:
func Float32bytes(float float32) []byte {
    bits := math.Float32bits(float)
    bytes := make([]byte, 4)
    binary.LittleEndian.PutUint32(bytes, bits)
    return bytes
}
我仍然不知道如何将它们转换回float32。
英文:
I'm working on a Go project and I would like to send float32 values using an UDPSocket.
The thing that I don't understand is what is the best way to convert these numbers to a byte buffer before sending them and how to convert them back to float32 after receiving them.
At the moment I'm converting float32->[]byte with the following function that I've found online, but I'm not even sure I'm getting what I want:
func Float32bytes(float float32) []byte {
    bits := math.Float32bits(float)
    bytes := make([]byte, 4)
    binary.LittleEndian.PutUint32(bytes, bits)
    return bytes
}
I still don't know how to convert them to float32.
答案1
得分: 3
例如,
package main
import (
	"encoding/binary"
	"fmt"
	"math"
)
func Float32Bytes(float float32) []byte {
	bits := math.Float32bits(float)
	bytes := make([]byte, 4)
	binary.LittleEndian.PutUint32(bytes, bits)
	return bytes
}
func BytesFloat32(bytes []byte) float32 {
	bits := binary.LittleEndian.Uint32(bytes)
	float := math.Float32frombits(bits)
	return float
}
func main() {
	pi := float32(math.Pi)
	b := Float32Bytes(pi)
	f := BytesFloat32(b)
	fmt.Println(f, f == pi, BytesFloat32(Float32Bytes(pi)) == pi)
}
输出:
3.1415927 true true
英文:
For example,
package main
import (
	"encoding/binary"
	"fmt"
	"math"
)
func Float32Bytes(float float32) []byte {
	bits := math.Float32bits(float)
	bytes := make([]byte, 4)
	binary.LittleEndian.PutUint32(bytes, bits)
	return bytes
}
func BytesFloat32(bytes []byte) float32 {
	bits := binary.LittleEndian.Uint32(bytes)
	float := math.Float32frombits(bits)
	return float
}
func main() {
	pi := float32(math.Pi)
	b := Float32Bytes(pi)
	f := BytesFloat32(b)
	fmt.Println(f, f == pi, BytesFloat32(Float32Bytes(pi)) == pi)
}
Output:
3.1415927 true true
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论