Gettings the most out of your bits

The following will produce the bit representation of an ord(byte) in python

def bit(chr, i=0, str=''):
    if i > 7: return str
    coef = (2**(8-i-1))
    if chr >= coef: return bit(chr-coef, i+1, str+'1')
    return bit(chr, i+1, str+'0')

Example

print bit(ord(“a”))
01100001

This entry was posted in Blog, Programming, Python, Snippets. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>