Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert binary32 to float in ruby

I have a binary32 encoded in IEEE 32.

How to convert 0x0040EDC2 to -118,625 ?

I have try several options of pack and unpack without success.

IEEE : http://en.wikipedia.org/wiki/Single-precision_floating-point_format

Manu

like image 201
manusvs650 Avatar asked Apr 14 '26 18:04

manusvs650


1 Answers

$ irb
irb(main):001:0> bin = "\x00\x40\xED\xC2"
=> "\000@\355\302"
irb(main):002:0> bin.unpack 'f'
=> [-118.625]
irb(main):003:0> bin.unpack 'e'
=> [-118.625]
irb(main):004:0> bin.unpack 'F'
=> [-118.625]
irb(main):005:0> i = 0x0040edc2
=> 4255170
irb(main):006:0> bin = [i].pack('L')
=> "\xC2\xED@\x00"
irb(main):007:0> bin.unpack 'g'
=> [-118.625]
irb(main):008:0> RUBY_PLATFORM
=> "x86_64-linux"
irb(main):009:0> RUBY_VERSION
=> "1.9.2"
like image 94
dbenhur Avatar answered Apr 16 '26 10:04

dbenhur



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!