Write bits in file

pataphor pataphor at gmail.com
Tue May 20 07:31:58 EDT 2008


On Sun, 18 May 2008 06:36:28 -0700 (PDT)
Monica Leko <monica.leko at gmail.com> wrote:

> Yes.  I need arbitrary, 8bits, than 10 bits for something else, than
> sequence of bytes, than 10 bits again, etc.

Here's something to get you started. No guarantees, but I managed to
write four 10 bit numbers to a file producing 5 bytes, saying hello. I
was just looking for an excuse to use send.

P.

def gen(f):
    L = []
 
    def flush(L):
        L.reverse()
        s = ''.join(map(str,L))
        j = int(s,2)
        f.write(chr(j))
    
    while 1:
        x = yield 
        if x in [0,1]:
            L.append(x)
        else:
            break
        if len(L) == 8:
            flush(L)
            L = []        
    if L:
        while len(L) < 8:
            L.append(0)
        flush(L)
    yield

def tenbits(i):
    for j in range(9,-1,-1):
        yield i >> j & 1

def charbits(s):
    for c in s:
        i = ord(c)
        for j in range(8):
            yield i >> j &1

def byten(L):
    while L:
        yield L[:10]
        L = L[10:]
        
def test():
    f = file('out.dat','w')
    g = gen(f)
    g.send(None)
    for x in [90,611,397,758]:
        for bit in tenbits(x):
            g.send(bit)
    g.send('stop')
    f.close()

def test1():
    bits = list(charbits('hello'))
    L = []
    for x in byten(bits):
        L.append(int(''.join(map(str,x)),2))
    print L
    
if __name__=='__main__':
    test()



More information about the Python-list mailing list