float32 to 4 bytes?

4,909 views
Skip to first unread message

Tai Trinh

unread,
Feb 23, 2012, 2:12:12 PM2/23/12
to golang-nuts

Hi.

How would i go about turning a float32 into 4 bytes?

And then turn 4 bytes back into a float32?

-Tai

John Asmuth

unread,
Feb 23, 2012, 2:16:07 PM2/23/12
to golan...@googlegroups.com

Tai Trinh

unread,
Feb 23, 2012, 2:20:17 PM2/23/12
to golang-nuts

Ah, silly me so how obvious. Very neat :)

Thanks!

-Tai

On 23 Feb, 20:16, John Asmuth <jasm...@gmail.com> wrote:
> http://weekly.golang.org/pkg/encoding/binary/#Write

Jan Mercl

unread,
Feb 23, 2012, 3:52:58 PM2/23/12
to golan...@googlegroups.com
On Thursday, February 23, 2012 8:12:12 PM UTC+1, Tai Trinh wrote:

How would i go about turning a float32 into 4 bytes?
 

And then turn 4 bytes back into a float32?

 

Paul Borman

unread,
Feb 24, 2012, 2:42:55 PM2/24/12
to Jan Mercl, golan...@googlegroups.com
That does not convert between a 32 bit native float and 4 bytes.  It converts to the specified byte order.  You can use unsafe to convert from 4 bytes in native byte order to a float 32.

    -Paul

Aram Hăvărneanu

unread,
Feb 24, 2012, 3:08:24 PM2/24/12
to Paul Borman, Jan Mercl, golan...@googlegroups.com
Vaxen are little endian.

--
Aram Hăvărneanu

Jan Mercl

unread,
Feb 25, 2012, 5:00:01 AM2/25/12
to golan...@googlegroups.com
On Friday, February 24, 2012 8:42:55 PM UTC+1, Paul Borman wrote:
That does not convert between a 32 bit native float and 4 bytes.  It converts to the specified byte order.  You can use unsafe to convert from 4 bytes in native byte order to a float 32.

On Thu, Feb 23, 2012 at 12:52 PM, Jan Mercl <jan.m...@nic.cz> wrote:
On Thursday, February 23, 2012 8:12:12 PM UTC+1, Tai Trinh wrote:

How would i go about turning a float32 into 4 bytes?
 

And then turn 4 bytes back into a float32?


I'm lost, that's IMO exactly what those function do: http://weekly.golang.org/src/pkg/math/unsafe.go
     9	// Float32bits returns the IEEE 754 binary representation of f.
    10	func Float32bits(f float32) uint32 { return *(*uint32)(unsafe.Pointer(&f)) }
    11	
    12	// Float32frombits returns the floating point number corresponding
    13	// to the IEEE 754 binary representation b.
    14	func Float32frombits(b uint32) float32 { return *(*float32)(unsafe.Pointer(&b)) }
 

Hotei

unread,
Feb 25, 2012, 1:34:32 PM2/25/12
to golang-nuts
I think if you get the bytes from a float32 and convert back on the
same system it should be ok. Crossing between different endian
systems would of course be subject to the requirement to swap the
order appropriately.

Paul Borman

unread,
Feb 27, 2012, 2:19:23 PM2/27/12
to Jan Mercl, golan...@googlegroups.com
Oh, sorry.  I had not actually seen those.  I was generalizing from the endian package which.  My mistake.

    -Paul
Reply all
Reply to author
Forward
0 new messages