Last active
August 29, 2015 14:04
-
-
Save domgetter/89bbc83a5636617f4020 to your computer and use it in GitHub Desktop.
convert float to bits
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
bits = eval("0x" + [0.15625].pack('g').unpack('H16')[0]).to_s(2).rjust(32,"0") | |
#=> "00111110001000000000000000000000" | |
# these are the bits of 0.15625 represented as a single precision float | |
sign = bits[0] | |
#=> "0" | |
exponent = bits[1..8] | |
#=> "01111100" | |
mantissa = bits[9..32] | |
#=> "01000000000000000000000" | |
sign = sign.to_i == 0 ? 1 : -1 | |
#=> 1 | |
exponent = 2**(eval("0b"+exponent)-127) | |
#=> (1/8) | |
mantissa_sum = 1 | |
#=> 1 | |
mantissa.each_char.each_with_index {|bit, index| mantissa_sum += bit.to_i*2**(-index-1)} | |
#=> "01000000000000000000000" | |
output = (sign*exponent*mantissa_sum).to_f | |
#=> 0.15625 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment