DeaD_EyE

float > binary

Feb 11th, 2020
120
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import struct
  2.  
  3.  
  4. def double_to_bin(value):
  5.     """
  6.    Convert an float to double (64 bit) binary representation
  7.    Please check here: http://www.binaryconvert.com/result_double.html
  8.  
  9.    """
  10.     value_sum = sum(
  11.         value << (shift * 8)
  12.         for shift, value in
  13.         enumerate(struct.pack('<d', value))
  14.     )
  15.     bin_str = f'{value_sum:064b}'
  16.     return {
  17.         'dec': value,
  18.         'hex': f'{value_sum:08x}',
  19.         'bin': bin_str,
  20.         'sign': bin_str[0] == '1',
  21.         'exponent': bin_str[1:12],
  22.         'mantissa': bin_str[12:],
  23.     }
RAW Paste Data