新聞中心
這里有您想知道的互聯(lián)網(wǎng)營銷解決方案
Python中字符串與二進制相互轉(zhuǎn)換的方法
小編給大家分享一下Python中字符串與二進制相互轉(zhuǎn)換的方法,相信大部分人都還不怎么了解,因此分享這篇文章給大家參考一下,希望大家閱讀完這篇文章后大有收獲,下面讓我們一起去了解一下吧!
創(chuàng)新互聯(lián)是一家專業(yè)的成都網(wǎng)站建設(shè)公司,我們專注成都網(wǎng)站建設(shè)、網(wǎng)站設(shè)計、網(wǎng)絡(luò)營銷、企業(yè)網(wǎng)站建設(shè),友情鏈接,廣告投放為企業(yè)客戶提供一站式建站解決方案,能帶給客戶新的互聯(lián)網(wǎng)理念。從網(wǎng)站結(jié)構(gòu)的規(guī)劃UI設(shè)計到用戶體驗提高,創(chuàng)新互聯(lián)力求做到盡善盡美。
簡單版本
def encode(s): return ' '.join([bin(ord(c)).replace('0b', '') for c in s]) def decode(s): return ''.join([chr(i) for i in [int(b, 2) for b in s.split(' ')]]) >>>encode('hello') '1101000 1100101 1101100 1101100 1101111' >>>decode('1101000 1100101 1101100 1101100 1101111') 'hello'
bitarray法
將二進制串轉(zhuǎn)化為bitarray對象,bitarray對象可以輕松轉(zhuǎn)化為bytes
from bitarray import bitarray def str2bitarray(s): ret = bitarray(''.join([bin(int('1' + hex(c)[2:], 16))[3:] for c in s.encode('utf-8')])) return ret def bitarray2str(bit): return bit.tobytes().decode('utf-8')
以上是“Python中字符串與二進制相互轉(zhuǎn)換的方法”這篇文章的所有內(nèi)容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內(nèi)容對大家有所幫助,如果還想學(xué)習(xí)更多知識,歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道!
分享標(biāo)題:Python中字符串與二進制相互轉(zhuǎn)換的方法
本文URL:http://www.ef60e0e.cn/article/gssjed.html