python中string和十六进制、二进制互转

 1 def str_to_hex(s):
 2     return ' '.join([hex(ord(c)).replace('0x', '') for c in s])
 3 
 4 def hex_to_str(s):
 5     return ''.join([chr(i) for i in [int(b, 16) for b in s.split(' ')]])
 6     
 7 def str_to_bin(s):
 8     return ' '.join([bin(ord(c)).replace('0b', '') for c in s])
 9     
10 def bin_to_str(s):
11     return ''.join([chr(i) for i in [int(b, 2) for b in s.split(' ')]])

 

posted on 2017-10-17 13:25  帅胡  阅读(23214)  评论(0编辑  收藏  举报

导航