通过UDP套接字发送float32值

huangapple go评论90阅读模式
英文:

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

huangapple
  • 本文由 发表于 2015年10月25日 19:01:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/33328907.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定