Skip to content

Instantly share code, notes, and snippets.

@sprout42
Created October 22, 2021 18:41
Show Gist options
  • Save sprout42/80a0b2fe76952582b4087be54ae36073 to your computer and use it in GitHub Desktop.
Save sprout42/80a0b2fe76952582b4087be54ae36073 to your computer and use it in GitHub Desktop.
Exploring floating point values
import struct
def single_info(val):
iee1754_val = struct.unpack('>I', struct.pack('>f', val))[0]
exp = (iee1754_val & 0x7F80_0000) >> 23
frac = iee1754_val & 0x007F_FFFF
result = (2**(exp-127)) * (1+(frac/(2**23)))
print('Single Precision:')
print('%08x: %03x %05x' % (iee1754_val, exp, frac))
print('%.60f' % result)
def double_info(val):
iee1754_val = struct.unpack('>Q', struct.pack('>d', val))[0]
exp = (iee1754_val & 0x7FF0_0000_0000_0000) >> 52
frac = iee1754_val & 0x00F_FFFF_FFFF_FFFF
result = (2**(exp-1023)) * (1+(frac/(2**52)))
print('Double Precision:')
print('%08x: %03x %05x' % (iee1754_val, exp, frac))
print('%.60f' % result)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment