字符串、數字與二進制轉換


# coding:utf-8
# 字符串轉換為二進制
def encodeStr(s):
    return ' '.join([bin(ord(c)).replace('0b', '') for c in s])
# 二進制轉換為字符串,解encodeStr的編碼。
def decodeStr(s):
    return ''.join([chr(i) for i in [int(b, 2) for b in s.split(' ')]])

# 測試:
s = encodeStr('八戒你瘦了!')
d = decodeStr(s)
print(s)
# 101000101101011 110001000010010 100111101100000 111011000100110 100111010000110 1111111100000001
print(d)
# 八戒你瘦了!

# 數字int型666轉換為二進制
encode_num = bin(666).replace('0b','')
# 二進制解碼轉換為int型編碼,也就是數字十進制
decode_num = int(encode_num,2)
print(encode_num)
# 1010011010
print(decode_num)
# 666

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM