在Python2.6或更高版本中,使用formatsyntax:'{0:0=#10b}'.format(my_num)[2:]
# '00001010'
Python字符串的一个优点是它们是序列。如果您只需要遍历字符,那么就不需要将字符串转换为列表。在
编辑:对于隐写术,您可能有兴趣将字符流转换为位流。下面是如何使用发电机来实现这一点:
^{pr2}$
要将比特流转换回字符流:def grouper(n, iterable, fillvalue=None):
# Source: http://docs.python.org/library/itertools.html#recipes
"grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx"
return itertools.izip_longest(*[iter(iterable)]*n,fillvalue=fillvalue)
def bits2str(bits):
for b in grouper(8,bits):
yield chr(int(''.join(map(str,b)),2))
例如,您可以像这样使用上述函数:for b in str2bits('Hi Zvarberg'):
print b,
# 0 1 0 0 1 0 0 0 0 1 1 0 1 0 0 1 0 0 1 0 0 0 0 0 0 1 0 1 1 0 1 0 0 1 1 1 0 1 1 0 0 1 1 0 0 0 0 1 0 1 1 1 0 0 1 0 0 1 1 0 0 0 1 0 0 1 1 0 0 1 0 1 0 1 1 1 0 0 1 0 0 1 1 0 0 1 1 1
# To show bits2str is the inverse of str2bits:
print ''.join([c for c in bits2str(str2bits('Hi Zvarberg'))])
# Hi Zvarberg
同样,大师Ned Batchelder使用Python和PIL here做了一些与隐写术相关的实验。你可以在那里找到一些有用的代码。在
如果您发现需要更高的速度(并且仍然希望用Python编写代码),那么您可能需要考虑使用numpy。在