I'm trying to convert a []uint8
byte slice into a float64
in GoLang. I can't find a solution for this issue online. I've seen suggestions of converting to a string first and then to a float64
but this doesn't seem to work, it loses it's value and I end up with zeroes.
Example:
metric.Value, _ = strconv.ParseFloat(string(column.Value), 64)
And it doesn't work...
type uint8 in Golang is the set of all unsigned 8-bit integers. The set ranges from 0 to 255. You should use type uint8 when you strictly want a positive integer in the range 0-255.
byte is an alias for uint8 and is equivalent to uint8 in all ways. byte is an alias for uint8 and is equivalent to uint8 in all ways. It is used, by convention, to distinguish byte values from 8-bit unsigned integer values.
For example,
package main import ( "encoding/binary" "fmt" "math" ) func Float64frombytes(bytes []byte) float64 { bits := binary.LittleEndian.Uint64(bytes) float := math.Float64frombits(bits) return float } func Float64bytes(float float64) []byte { bits := math.Float64bits(float) bytes := make([]byte, 8) binary.LittleEndian.PutUint64(bytes, bits) return bytes } func main() { bytes := Float64bytes(math.Pi) fmt.Println(bytes) float := Float64frombytes(bytes) fmt.Println(float) }
Output:
[24 45 68 84 251 33 9 64] 3.141592653589793
I think this example from Go documentation is what you are looking for: http://golang.org/pkg/encoding/binary/#example_Read
var pi float64 b := []byte{0x18, 0x2d, 0x44, 0x54, 0xfb, 0x21, 0x09, 0x40} buf := bytes.NewReader(b) err := binary.Read(buf, binary.LittleEndian, &pi) if err != nil { fmt.Println("binary.Read failed:", err) } fmt.Print(pi)
Prints 3.141592653589793
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With