how can i convert a float64 to a []uint8

1,089 views
Skip to first unread message

Sven Lange

unread,
Feb 20, 2011, 10:17:22 AM2/20/11
to golang-nuts
hi there!

i want to send a value over the network via websocket.

the value is float64 and must be converted to []uint8 .

could someone pls help me. i am stuck at the moment.

thx
s

conversion

Florian Weimer

unread,
Feb 20, 2011, 11:00:01 AM2/20/11
to Sven Lange, golang-nuts
* Sven Lange:

> i want to send a value over the network via websocket.
>
> the value is float64 and must be converted to []uint8 .

You can access the bit pattern using math.Float64bits().

Sven Lange

unread,
Feb 20, 2011, 11:50:44 AM2/20/11
to golang-nuts
i found a nice way to convert a float64 to a []byte or []uint8

there is the package strconv that is a good helper.

value := math.Sin(3.) // this is my float64 value
msg := strconv.Ftoa64(value, 'g', 10) // conversion to string
out := []byte(msg) // conversion to []byte // final conversion to []byte

Henry Heikkinen

unread,
Feb 20, 2011, 11:59:15 AM2/20/11
to golang-nuts
binary.LittleEndian.PutUint64(yourByteSlice[0:8],
math.Float64bits(yourFloat64))

Change LittleEndian to BigEndian if needed. I'm using this in my
network packet construction package.

John Asmuth

unread,
Feb 20, 2011, 12:13:49 PM2/20/11
to golang-nuts
theBytes := *(*[8]byte)(unsafe.Pointer(&theFloat64))
theBytes := *(*[4]byte)(unsafe.Pointer(&theFloat32))

Lars Pensjö

unread,
Feb 20, 2011, 1:42:06 PM2/20/11
to golan...@googlegroups.com
Using the package json is nice, except that data is encoded in ASCII and so may use more bandwidth.

You may also consider to convert the value into fixed point, depending on what your requirements are on precision and range.
Reply all
Reply to author
Forward
0 new messages