Binary representation of floating point numbers

Bengt Richter bokr at oz.net
Tue Dec 6 21:25:00 EST 2005


On Tue, 06 Dec 2005 22:51:03 -0000, Grant Edwards <grante at visi.com> wrote:

>On 2005-12-06, 63q2o4i02 at sneakemail.com <63q2o4i02 at sneakemail.com> wrote:
>
>> The only way to get the flags is as a float, either through an
>> ascii string or a true float.
>
>That's perverse.  
>
>Really.
>
>Somebody needs to be slapped.
>
>> The value of the float, however, is representable as 24 bits
>> of normal binary.
>
>OK, that should preserve a 1:1 mapping between strings/floats
>and flag bit patterns.  It's still sick, though.
>
>> So for example, the value returned is +4.608400E+04 which is
>> really an int, 46084, which is more easily convertible to
>> binary.
>
>You really don't need to convert it to "binary".  Just convert
>it to an integer object.
>
>> So the question becomes how to convert an int to binary, which
>> I found here
>>
>> http://groups.google.com/group/comp.lang.python/browse_frm/thread/300e220394e2d841/33bc9b0d8174b038?lnk=st&q=python+int+to+binary&rnum=1#33bc9b0d8174b038
>
>I doubt you actually want to do that.  Just leave it as an
>integer, and test for the bits you care about:
>
>def bit(n):
>   return 1<<n
>
>flags = int(half_assed_float_representing_the_flag_values)
>
>if flags & bit(0):
>    print "underrange"
>if flags & bit(1):
>    print "overrange"
>if flags & bit(19):
>    print "bit 19 is set but nobody can hear me scream"
>if flags & bit(23):
>    callThePolice()
>
>or whatever.
>
You could also make a "whatever" like

 >>> class Bitview(long):
 ...     def __new__(cls, v, width=32):
 ...         inst = long.__new__(cls, v)
 ...         inst.width = width
 ...         return inst
 ...     def __getitem__(self, i):
 ...         if isinstance(i, slice): return list(self)[i]
 ...         if i>=self.width or i+self.width<0:
 ...             raise IndexError, '%r has only %r bits' %(long(self), self.width)
 ...         if i<0: i = i + self.width
 ...         bit = 1<<i
 ...         return self&bit and 1 or 0
 ...     def __repr__(self): return "Bitview(int('%s', 2))"% str(self)
 ...     def __str__(self): return ''.join(map(str, self))[::-1]
 ...
 >>> bv11 = Bitview(11, 8)
 >>> bv11
 Bitview(int('00001011', 2))
 >>> bv11[8]
 Traceback (most recent call last):
   File "<stdin>", line 1, in ?
   File "<stdin>", line 9, in __getitem__
 IndexError: 11L has only 8 bits
 >>> list(bv11)
 [1, 1, 0, 1, 0, 0, 0, 0]
 >>> bv11[::-1]
 [0, 0, 0, 0, 1, 0, 1, 1]
 >>> bv11[-1]
 0
 >>> bv11[-5]
 1
 >>> bv11[-6]
 0
 >>> bv11[:4]
 [1, 1, 0, 1]
 >>> str(bv11)
 '00001011'
 >>> repr(bv11)
 "Bitview(int('00001011', 2))"
 >>> eval(repr(bv11)) == bv11
 True
 >>> import sys
 >>> Bitview(sys.maxint)
 Bitview(int('01111111111111111111111111111111', 2))

Add niceties to taste ;-)
Regards,
Bengt Richter



More information about the Python-list mailing list