Created
September 25, 2013 21:06
-
-
Save inducer/6706057 to your computer and use it in GitHub Desktop.
Floating point structure playground
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
from __future__ import division | |
def pretty_print_fp(x): | |
print "---------------------------------------------" | |
print "Floating point structure for %r" % x | |
print "---------------------------------------------" | |
import struct | |
s = struct.pack("d", x) | |
print "Hex pattern:", " ".join("%02x" % ord(i) for i in s[::-1]) | |
def get_bit(i): | |
byte_nr, bit_nr = divmod(i, 8) | |
return int(bool( | |
ord(s[byte_nr]) & (1 << bit_nr) | |
)) | |
def get_bits(lsb, count): | |
return sum(get_bit(i+lsb)*2**i for i in xrange(count)) | |
# https://en.wikipedia.org/wiki/Double_precision_floating-point_format | |
print "Sign bit (1:negative):", get_bit(63) | |
exponent = get_bits(52, 11) | |
print "Exponent: %d (unshifted: %d)" % (exponent - 1023, exponent) | |
mantissa = get_bits(0, 52) | |
print "Mantissa:", hex(mantissa) | |
mantissa_with_one = mantissa + 2**52 | |
print "Mantissa with implied one:", hex(mantissa_with_one) | |
mantissa_with_one = mantissa + 2**52 | |
print "Shifted Mantissa with implied one:", mantissa_with_one / (2**52) | |
pretty_print_fp(1+2**-52) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment