Skip to content

Instantly share code, notes, and snippets.

@inducer
Created September 25, 2013 21:06
Show Gist options
  • Save inducer/6706057 to your computer and use it in GitHub Desktop.
Save inducer/6706057 to your computer and use it in GitHub Desktop.
Floating point structure playground
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