Float to binary

前端 未结 6 2174
醉话见心
醉话见心 2020-12-25 10:17

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 th

6条回答
  •  北海茫月
    2020-12-25 10:41

    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;
    

提交回复
热议问题