python 字符串与16进制 转化

时间:2021-09-05 20:18:14
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, ) for b in s.split(r'/x')[:]]]) 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, ) 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, ) 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, ) for b in s.split(' ')]]) a="abcdef"
x=str_to_hex(a)
print(x)
print(hex_to_str(x))

输出

abcdef
[Program finished]