How do you convert array of byte to array of float64

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

How do you convert array of byte to array of float64

问题

我正在寻找将字节数组([]byte)转换为浮点数数组([]float64)的方法,但我没有任何线索来做到这一点。

我从rtlsdr包(https://pkg.go.dev/github.com/jpoirier/gortlsdr)中读取数据,并希望将其传递给Pwelch算法(https://pkg.go.dev/github.com/mjibson/go-dsp/spectral)。

是否可能将大型字节数组转换为float64?

(+另一个问题:您认为是否可能将Pwelch函数转换为使用uint8?)

非常感谢,
pefr

英文:

I am searching to convert an array of byte ([]byte) to array of float64 ([]float64) but I didn't have any clues to do it.

I read data from rtlsdr package (https://pkg.go.dev/github.com/jpoirier/gortlsdr) and would pass it to Pwelch algorithm (https://pkg.go.dev/github.com/mjibson/go-dsp/spectral)

Is it possible to convert large array of byte to float64 ?

(+ another question: did you think that possible to convert Pwelch function to work with uint8 ?)

Thank you so much,
pefr

答案1

得分: 1

byte/uint8有8位,float64有64位。你可以像这样将[8]byte转换为float64

package main

import (
	"encoding/binary"
	"fmt"
	"math"
)

func main() {
    in := 1.0

	// 将float64转换为[8]byte
	var bytes [8]byte
	binary.LittleEndian.PutUint64(bytes[:], math.Float64bits(in))

	// 将[8]byte转换为float64
	out := math.Float64frombits(binary.LittleEndian.Uint64(bytes[:]))

    fmt.Println(out)
}

你可能想选择binary.BigEndian。这符合你的需求吗?或者你想将长度为8n的byte数组转换为长度为n的float64数组吗?请随意发表评论 How do you convert array of byte to array of float64

英文:

byte/uint8 has 8 bits, float64 has 64. You can convert [8]byte to float64 like this:

package main

import (
	"encoding/binary"
	"fmt"
	"math"
)

main()
{
    in := 1.

	// Convert float64 to [8]byte
	var bytes [8]byte
	binary.LittleEndian.PutUint64(bytes[:], math.Float64bits(in))

	// Convert [8]byte to float64
	out := math.Float64frombits(binary.LittleEndian.Uint64(bytes[:]))

    fmt.Println(out)
}

You may want to chose binary.BigEndian instead.

Is that what you are looking for? Or do you want to convert an array of byte with length 8n to an array of float64 with length n? Feel free to comment How do you convert array of byte to array of float64

huangapple
  • 本文由 发表于 2022年9月19日 19:10:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/73772460.html
匿名

发表评论

匿名网友

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

确定