Bitmask representation of integers

Scott David Daniels Scott.Daniels at Acm.Org
Wed Oct 8 10:50:19 EDT 2003


Tonguç Yumruk wrote:
> Hi,
> 
> I'm looking for a way to represent bit-level data in python. Something
> like 0xDEADBEEF representation, but not for hex i'm looking for binary.
> Something like the %00110101 representation I used in pascal... Of
> course I can make my operations with ordinary integers but binary
> representation makes the code easier to read.
> 
octal is a simple starting point:

_octalchunks = '000', '001', '010', '011', '100', '101', '110', '111'

_encoder = dict(enumerate(_octalchunks))
_decoder = dict([(txt, str(n)) for n, txt in _encoder.items()
                          + [(0,''),   (0,'0'), (1,'1'),
                            (0,'00'), (1,'01'), (2,'10'), (3,'11')]])

def tobinary(number):
     initial = ''.join([_encoder[digit] for digit in oct(number)])
     # but the above certainly has too many leading zeroes, so:
     return initial.lstrip('0') or '0'


def frombinary(text):
     firstdigitlen = len(text) % 3
     digits = [_decoder[text[n:n+3]]
               for n in range(firstdigitlen, len(text), 3)]
     digits.insert(0, _decoder[text[:firstdigitlen]])
     return int(''.join(digits), 8)

if __name__ == '__main__':
     tests = [ (0,'0'), (5,'101'), (15,'1111'), (16,'10000')]

     for n,t in tests:
         assert t == tobinary(n)
         assert n == frombinary(t)
         assert n == frombinary('0'+t)
         assert n == frombinary('00'+t)
         assert n == frombinary('000'+t)



-Scott David Daniels
Scott.Daniels at Acm.Org





More information about the Python-list mailing list