Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert byte slice "[]uint8" to float64 in GoLang

Tags:

arrays

go

uint8t

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...

like image 988
user3435186 Avatar asked Mar 18 '14 21:03

user3435186


People also ask

What is [] uint8 in Golang?

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.

Is uint8 a byte?

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.


2 Answers

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 
like image 184
peterSO Avatar answered Sep 17 '22 07:09

peterSO


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

like image 43
Kluyg Avatar answered Sep 18 '22 07:09

Kluyg