当前位置:   article > 正文

Python3小程序:把字符串转换成连续的UTF8编码(16位)_binascii.hexlify(ciphertext).decode('utf-8')

binascii.hexlify(ciphertext).decode('utf-8')
  1. # coding: utf-8
  2. import binascii
  3. '''
  4. 参考代码1
  5. mystery = b"\xe5\x88\xab"
  6. x = mystery.decode('utf-8')
  7. print(x)
  8. y = bytearray.fromhex(\xe5\x88\xab).decode()
  9. print(y)
  10. '''
  11. '''
  12. 参考代码2
  13. var = 1
  14. while var == 1:
  15. a = str(input('请输入字符串:\n'))
  16. b = []
  17. for i in a:
  18. c = hex(ord(i))
  19. print(c)
  20. # print('转换结果为:\n\n\n{}\n\n'.format(x))
  21. '''
  22. '''
  23. 参考代码3
  24. x = '\x53\x21\x6a'
  25. y = [eval(hex(ord(c))) for c in x]
  26. print(y)
  27. k = bytearray(y)
  28. z = binascii.b2a_hex(k)
  29. print(z)
  30. '''
  31. var = 1
  32. while var == 1:
  33. a = str(input('请输入字符串:\n'))
  34. b = []
  35. for i in a:
  36. c = i.encode('utf8')
  37. #print(c)
  38. y = [eval(hex(j)) for j in c]
  39. #print(y)
  40. k = bytearray(y)
  41. z = str(binascii.b2a_hex(k))
  42. #print(z)
  43. z = z.replace('b','',1)
  44. #print(z)
  45. b.append(eval(z))
  46. #print (b)
  47. p = ''.join(b)
  48. print('转换结果为:\n\n{}\n'.format(p))

例:

输入:呵呵123abc!@#

输出:e591b5e591b5313233616263214023

==========================================================

2019-04-18更新:调用binascii库更简单的代码

  1. import binascii
  2. def main(a):
  3. return binascii.hexlify(a.encode('utf8')).decode('utf8')
  4. if __name__ == '__main__':
  5. var = 1
  6. while var == 1:
  7. a = input('请输入字符串:\n')
  8. print('转换为utf8的16进制编码,结果为:\n\n{}\n'.format(main(a)))

 

用之前写的Python3小程序:把连续的16进制UTF8编码转换为字符串检测一下,结果正确。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/IT小白/article/detail/678858
推荐阅读
相关标签
  

闽ICP备14008679号