bits to string python

巧了我就是萌 提交于 2019-12-11 03:22:51

问题


I have used this function to convert string to bits.

def a2bits(chars):
     return bin(reduce(lambda x, y : (x<<8)+y, (ord(c) for c in chars), 1))[3:]

How would I go about doing the reverse? Bits to string. Would I have to separate the bits into ASCII numbers and then convert them into characters?

I got the function a2bits from this site: http://www.daniweb.com/software-development/python/code/221031/string-to-bits

Is there something in the standard library to convert bits to string?


回答1:


>>> def bits2a(b):
...     return ''.join(chr(int(''.join(x), 2)) for x in zip(*[iter(b)]*8))
... 
>>> bits2a('0110100001100101011011000110110001101111')
'hello'



回答2:


import base64
str(base64.b16decode(hex(int("0110100001100101", base=2))[2:],casefold=True))[2:-1]


来源:https://stackoverflow.com/questions/9916334/bits-to-string-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!