Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Float to binary

I'm trying to convert a floating point number to binary representation; how can I achieve this? My goal is, however, not to be limited by 2m so I'm hoping for something that could be easily extended to any base (3, 4, 8) ecc.

I've got a straightforward implementation so far for integers:

import string

LETTER = '0123456789' + string.ascii_lowercase
def convert_int(num, base):
    if base == 1:
        print "WARNING! ASKING FOR BASE = 1"
        return '1' * num if num != 0 else '0'

    if base > 36: raise ValueError('base must be >= 1 and <= 36')

    num, rest = divmod(num, base)
    rest = [LETTER[rest]]
    while num >= base:
        num, r = divmod(num, base)
        rest.append(LETTER[r])
    rest.reverse()
    return (LETTER[num] if num else '') + ''.join(str(x) for x in rest)

any help appreciated :)

edit:

def convert_float(num, base, digits=None):
    num = float(num)
    if digits is None: digits = 6

    num = int(round(num * pow(base, digits)))
    num = convert_int(num, base)
    num = num[:-digits] + '.' + num[:digits]
    if num.startswith('.'): num = '0' + num
    return num

is that right? why do i get this behaviour?

>>> convert_float(1289.2893, 16)
'509.5094a0'
>>> float.hex(1289.2983)
'0x1.42531758e2196p+10'

p.s. How to convert float number to Binary?

I've read that discussion, but I don't get the answer.. I mean, does it work only for 0.25, 0.125? and I dont understand the phrase 'must be in reverse order'...

like image 733
Ant Avatar asked Jan 29 '11 19:01

Ant


People also ask

Can you convert float to binary in Python?

Python doesn't provide any inbuilt method to easily convert floating point decimal numbers to binary number.

What is 0.75 binary?

The decimal number 0.75 is written as 0.11 in binary.

How floats are stored in binary?

Scalars of type float are stored using four bytes (32-bits). The format used follows the IEEE-754 standard. The mantissa represents the actual binary digits of the floating-point number.

How do you write 0.5 in binary?

How do you represent 0.5 in binary? Multiply the 0.5 by 2 : 0.5 × 2 = 1.0 . Since the result is 1 , add 1 to the binary fraction: 0.1 . The remaining decimal part of the number is zero; thus, the representation is complete!


3 Answers

For floats there is built-in method hex().

http://docs.python.org/library/stdtypes.html#float.hex

It gives you the hexadecimal representation of a given number. And translation form hex to binary is trivial.

For example:

In [15]: float.hex(1.25)
Out[15]: '0x1.4000000000000p+0'

In [16]: float.hex(8.25)
Out[16]: '0x1.0800000000000p+3'
like image 179
stmi Avatar answered Nov 11 '22 15:11

stmi


If you want to convert a float to a string with d digits after the decimal radix point:

  1. Multiply the number by base**d.
  2. Round to the nearest integer.
  3. Convert the integer to a string.
  4. Insert the . character d digits before the end.

For example, to represent 0.1 in base 12 with 4 decimal dozenal places,

  1. 0.1 × 124 = 2073.6
  2. Round to nearest integer → 2074
  3. Convert to string → 124A
  4. Add radix point → 0.124A
like image 30
dan04 Avatar answered Nov 11 '22 16:11

dan04


This isn't the same style of binary representation that you want, but this will convert an IEEE 754 into it's sign, mantissa and base, which can be used to create a hex representation in a fairly straightforward fashion. Note that the 'value' of the mantissa is 1+BINARY, where BINARY is the binary representation - hence the -1 in the return.

I wrote this code and am declaring it public domain.

    def disect_float(f):
      f = float(f); #fixes passing integers
      sign = 0x00; #positive
      exp = 0;
      mant = 0;
      if(f < 0): #make f positive, store the sign
        sign = '-'; #negative
        f = -f;
      #get the mantissa by itself
      while(f % 1 > 0): #exp is positive
        f*=2
        exp+=1
      #while(f % 1 > 0):
      tf = f/2;
      while(tf % 1 <= 0): #exp is negative
        exp-=1;
        f=tf;
        tf=f/2;
        if(exp < -1024): break;
      mant=int(f);
      return sign, mant-1, exp;
like image 21
S James S Stapleton Avatar answered Nov 11 '22 15:11

S James S Stapleton