Skip to content

Instantly share code, notes, and snippets.

@nagachika
Created November 9, 2009 04:29
Show Gist options
  • Save nagachika/229688 to your computer and use it in GitHub Desktop.
Save nagachika/229688 to your computer and use it in GitHub Desktop.
IEEE 754 (double precision) decode practice.
def ieee754_double(num)
int64 = [num].pack("d").unpack("Q")[0]
sign = (int64 & (1 << 63)) == 0 ? 1 : -1
exp = (int64 & 0x7ff0000000000000) >> 52
frac = (int64 & 0x000fffffffffffff)
if exp == 0 and frac == 0
return sign * 0.0
end
if exp == 0x7ff
if frac == 0
# +Infinity/-Infinity
return sign * (1.0 / 0.0)
else
# NaN
return (0.0 / 0.0)
end
end
if exp != 0
# regular number
exp -= 0x3ff
frac += 0x0010000000000000
else
# non regular number
exp -= 0x3fe
end
return sign * (frac * (2.0 ** -52)) * (2.0 ** exp)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment