Help with converting function to Ruby code

Hey there. I have a GOlang code which converts a 32 bit single precision hex to float, I need to implement it in a Ruby project, I’ve been searching for long days without success. Could anyone gimme a ltl help? Below my go code I need to write in Ruby;

https://play.golang.org/p/gWOv6g2HEQD

Any help would be appreciated. Tnx.

This works in Ruby 1.9.3 and was good practice for a rubynewbee.
Likely there are easier ways available in later versions of Ruby.

def hex_to_f(hex)
b=sprintf “%b”, hex
sign = (b[0]==‘0’) ? 1 : -1
exp=b[1…8]
mant=b[9…31]
# String.each_char works left-right so reverse to take the LSD first
e=0
m=0
exp.reverse.each_char{|c| if(c==‘1’) then e+=2**m; end; m+=1}
exponent = e - 127
f=1.0
m=1
mant.each_char{|c| if(c==‘1’) then f+=1/2.0 ** m; end; m+=1}
f * 2 ** exponent * sign
end

hex_to_f ‘0xc1dccb61’
=> -27.599306106567383

There is indeed an easier way available, and it is also available in 1.9.3:

0xffff.to_f # => 65535.0

The OP didn’t ask for a string input. But if you did want a string input, here’s a one-liner that will convert a stringified number with any base:

def string_to_float(string, base = 10)
  string.delete('.').to_i(base).to_f / base**(string.reverse.index('.') || 0)
end

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs