[Python] 十六进制整数与ASCii编码字符串相互转换

来源:互联网 发布:jsp在线考试系统源码 编辑:程序博客网 时间:2024/06/05 02:29

在使用Pyserial与STM32进行通讯时,遇到了需要将十六进制整数以Ascii码编码的字符串进行发送并且将接收到的Ascii码编码的字符串转换成十六进制整型的问题。查阅网上的资料后,均没有符合要求的,遂结合各家之长,用了以下方法。

环境

  • Python2.7 + Binascii模块

十六进制整数转ASCii编码字符串

# -*- coding: utf-8 -*-import binascii#16进制整数转ASCii编码字符串a = 0x665554b = hex(a)  #转换成相同的字符串即'0x665554'b = b[2:]   #截取掉'0x'c = binascii.a2b_hex(b) #转换成ASCii编码的字符串print("a:%x, b:%s,c:%s" %(a,b,c))print type(a)print type(b)print type(c)
  • 测试结果:
a:665554, b:665554,c:fUT<type 'int'><type 'str'><type 'str'>

ASCii编码字符串转十六进制整数

# -*- coding: utf-8 -*-import binasciic = 'fUT'e = 0   #暂存结果for i in c:    d = ord(i)  #单个字符转换成ASCii码    e = e*256 + d   #将单个字符转换成的ASCii码相连print("e:%x" %e)print type(e)
  • 测试结果:
e:665554<type 'int'>

可以看到,以上两段小程序顺利实现了这个设计要求

1 0
原创粉丝点击