[Python-Dev] Issue 3008: Binary repr of floats (original) (raw)

Raymond Hettinger python at rcn.com
Sat Jul 19 06:06:54 CEST 2008


The new float.hex() is really nice. Would like to augment it with a matching float.bin() method using the same notation and normalization and leaving all the rightmost bits as Guido suggested. I think this would help demystify floats and make it straightforward to show exactly what is happening during a floating point calculation that is losing precision.

def float_as_bin(x): '3.125 --> -0b1.1101000000000000000000000000000000000000000000000000p+1' hex2bin = {'0' : '0000', '1' : '0001', '2' : '0010', '3' : '0011', '4' : '0100', '5' : '0101', '6' : '0110', '7' : '0111', '8' : '1000', '9' : '1001', 'a' : '1010', 'b' : '1011', 'c' : '1100', 'd' : '1101', 'e' : '1110', 'f' : '1111'} hex_pattern = '(-)?0x([0-9a-f]+).([0-9a-f])(.)' sign, intpart, fracpart, exp = re.search(hex_pattern, x.hex().lower()).groups() return ((sign or '') + '0b' + intpart + '.' + ''.join(hex2bin[d] for d in fracpart)[:53] + exp)

The implementation would re-use Mark's code, substituting binary output for hex in the fractional part.

Raymond



More information about the Python-Dev mailing list