Created
November 9, 2009 04:29
-
-
Save nagachika/229688 to your computer and use it in GitHub Desktop.
IEEE 754 (double precision) decode practice.
This file contains 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
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