donderdag 9 april 2015

The 8 bit prototype.

For practical implementations of the algorithm discussed in the previous posting, the following python code may be used as a prototype.

class SBE8_(): #optimal stop bit encoding of arbitrary int values at char size 8
    def enc(self, I):
        L=1 #nr chars in encoding
        Vo=1<<7 #overfow value of one character
        while I>=Vo:
            I-=Vo
            L+=1
            Vo=Vo<<7 #overflow value of L characters
        Enc=bytearray()
        Sbit=128 #stop bit termination value
        Vo=1<<7
        while L:
            I,Vc=divmod(I,Vo)
            Enc.insert(0,Sbit+Vc)
            Sbit=0 #continue value of stop bit
            L-=1
        return Enc           

    def dec(self, Enc):
        I=Enc.pop(0)
        Sbit=I&128
        I=I&127
        if Sbit: #done decoding
            return I
        L=0 #nr characters processed minus 1
        while not Sbit:
            Vc=Enc.pop(0)
            Sbit=Vc&128
            Vc=Vc&127
            I=(I<<7)+Vc #add character payload value
            L+=1
        while L:
            I+=(1<<L*7) #add character overflow value
            L-=1
        return I

Suggestions for a better algorithm and improved implementations are most welcome.

Geen opmerkingen:

Een reactie posten