python 字符串与16进制 转化

 

def str_to_hex(s):
    return r"/x"+r'/x'.join([hex(ord(c)).replace('0x', '') for c in s])

def hex_to_str(s):
    return ''.join([chr(i) for i in [int(b, 16) for b in s.split(r'/x')[1:]]])
    
def str_to_bin(s):
    return ' '.join([bin(ord(c)).replace('0b', '') for c in s])
    
def bin_to_str(s):
    return ''.join([chr(i) for i in [int(b, 2) for b in s.split(' ')]])
    
a="abcdefg"
x=str_to_hex(a)
print(x)
print(hex_to_str(x))

输出:

/x61/x62/x63/x64/x65/x66/x67
abcdefg                                                     
[Program finished]

 

demo2

def str_to_hex(s):
    return ' '.join([hex(ord(c)).replace('0x', '') for c in s])

def hex_to_str(s):
    return ''.join([chr(i) for i in [int(b, 16) for b in s.split(' ')]])
    
def str_to_bin(s):
    return ' '.join([bin(ord(c)).replace('0b', '') for c in s])
    
def bin_to_str(s):
    return ''.join([chr(i) for i in [int(b, 2) for b in s.split(' ')]])
    
a="abcdef"
x=str_to_hex(a)
print(x)
print(hex_to_str(x))

输出

61 62 63 64 65 66
abcdef                                                    
[Program finished]

 

posted @ 2019-04-19 12:56  anobscureretreat  阅读(19902)  评论(0编辑  收藏  举报