python 字符串转字节串

时间:2021-11-22 17:04:37
def encode(s):
	result = ''
	index = 1
	for c in s:
		v = hex(ord(c)).replace('0x', '')
		if len(v) == 1:
			v = '0' + v
		result += v
		if index % 32 == 0:
			result += '\n'
		elif index % 4 == 0:
			result += ' '
		index += 1
	print result
	return result
def decode(s):
	s = s.replace(' ', '')
	s = s.replace('\n', '')
	result = ''
	index = 1
	cc = ''
	for c in s:
		cc += c
		if index % 2 == 0:
			result += chr(int(cc, 16))
			cc = ''
		index += 1
	print result
	return result