Binary representation of float in Python (bits not hex) -
how string binary ieee 754 representation of 32 bit float?
example
1.00 -> '00111111100000000000000000000000'
you can struct
package:
import struct def binary(num): return ''.join(bin(ord(c)).replace('0b', '').rjust(8, '0') c in struct.pack('!f', num))
that packs network byte-ordered float, , converts each of resulting bytes 8-bit binary representation , concatenates them out:
>>> binary(1) '00111111100000000000000000000000'
edit: there request expand explanation. i'll expand using intermediate variables comment each step.
def binary(num): # struct can provide float packed bytes. '!' ensures # it's in network byte order (big-endian) , 'f' says should # packed float. alternatively, double-precision, use 'd'. packed = struct.pack('!f', num) print 'packed: %s' % repr(packed) # each character in returned string, we'll turn corresponding # integer code point # # [62, 163, 215, 10] = [ord(c) c in '>\xa3\xd7\n'] integers = [ord(c) c in packed] print 'integers: %s' % integers # each integer, we'll convert binary representation. binaries = [bin(i) in integers] print 'binaries: %s' % binaries # strip off '0b' each of these stripped_binaries = [s.replace('0b', '') s in binaries] print 'stripped: %s' % stripped_binaries # pad each byte's binary representation's 0's make sure has 8 bits: # # ['00111110', '10100011', '11010111', '00001010'] padded = [s.rjust(8, '0') s in stripped_binaries] print 'padded: %s' % padded # @ point, have each of bytes network byte ordered float # in array binary strings. concatenate them total # representation of float: return ''.join(padded)
and result few examples:
>>> binary(1) packed: '?\x80\x00\x00' integers: [63, 128, 0, 0] binaries: ['0b111111', '0b10000000', '0b0', '0b0'] stripped: ['111111', '10000000', '0', '0'] padded: ['00111111', '10000000', '00000000', '00000000'] '00111111100000000000000000000000' >>> binary(0.32) packed: '>\xa3\xd7\n' integers: [62, 163, 215, 10] binaries: ['0b111110', '0b10100011', '0b11010111', '0b1010'] stripped: ['111110', '10100011', '11010111', '1010'] padded: ['00111110', '10100011', '11010111', '00001010'] '00111110101000111101011100001010'
Comments
Post a Comment