hey guys...
I just need a little help with my encoder...

this is the problem:
Click Here

my code:

def f(byte_size,value):
    e=((byte_size*8)-1)//(byte_size+1)+(byte_size>2)*byte_size//2
    m,b=[((byte_size*8)-(1+e)), ~(~0 << e-1)]

    OS= '1' if value<0 else '0' #sign

    I,F=str(abs(value)).split('.')
    I=bin(int(I)).replace('0b','')

    FB=''
    l=0; r = int(''.join(['1']*e),2)+m
    while l<r:
        B,F=str(float('0.'+F)*2.).split('.')
        FB+=B
        if F=='0': break
        l+=1

    #print FB
    E=0
    M=''
    if I=='0':
        while True:
            if FB[-E]=='0': E-=1
            else: break
        M=FB[-E:-E+m]
        E+=2-b #not sure why I need 2 when I should only need 1
    else:
        E=(len(I)-1)-b
        M=(I+FB)[1:1+m]

    E = bin(E+int('1'*(e-1))).replace('0b','')
    OE = ('0'*(e-len(E)))+E if len(E)<e else E[0:e]
    OM = ('0'*(m-len(M)))+M if len(M)<m else M[0:m]

    print OS+' '+OE+' '+OM

sorry for the sloppy coding... >_<
I should've commented a little more.
and I know string handling is quite slow...
I'll handle by binary later.

also, the encoder was built to encode floats of any specified byte-length

Recommended Answers

All 5 Replies

if this has already been figured out, please link me to the thread :/

I wrote a module anyfloat for you in a previous thread, which does exactly this, why don't you use it ?

>>> from anyfloat import anyfloat
>>> anyfloat.from_float(1.6875).bin((3, 4))
'0 011 1011'
>>> anyfloat.from_float(-1313.3125).bin((8, 23))
'1 10001001 01001000010101000000000'
>>> anyfloat.from_float(0.1015625).bin((8, 23))
'0 01111011 10100000000000000000000'

I've tried to understand the class programming last time and can't...
my code doesn't contain a single class so conversion is hard for me :/
(classes are a completely different story with me)

I want to implament the code from your module directly into my __BIN() function.

The algorithm in module anyfloat is this

python float (= C double, assumed 64 bits (called size (11,52) in module))
    --->  converted into a 64 bits integer (called an ieee integer)
    ---> cut in 3 parts: sign, exponent, significand (integers)
    ---> transformed to: sign', exponent', significand' (the anyfloat, wich meaning differs from ieee, it's independent from the floating point size)
    ---> transformed again to: sign, exponent, significand for another ieee format, say 32 bits (8,23)
    ---> the integers are transformed to strings with 0s ans 1s and joined.

You can rewrite the module as a set of functions if you don't like classes.

alright thanx :)

not marking solved just yet due to needed testing

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.