Python3bytes、hex、字符串之间相互转换
生活随笔
收集整理的这篇文章主要介绍了
Python3bytes、hex、字符串之间相互转换
小编觉得挺不错的,现在分享给大家,帮大家做个参考.
1、字符串转bytes
string to bytes eg: '0123456789ABCDEF0123456789ABCDEF' b'0123456789ABCDEF0123456789ABCDEF' ''' def stringTobytes(str):return bytes(str,encoding='utf8')
2、bytes转字符串
''' bytes to string eg: b'0123456789ABCDEF0123456789ABCDEF' '0123456789ABCDEF0123456789ABCDEF' ''' def bytesToString(bs):return bytes.decode(bs,encoding='utf8')
3、十六进制字符串转bytes
''' hex string to bytes eg: '01 23 45 67 89 AB CD EF 01 23 45 67 89 AB CD EF' b'\x01#Eg\x89\xab\xcd\xef\x01#Eg\x89\xab\xcd\xef' ''' def hexStringTobytes(str):str = str.replace(" ", "")return bytes.fromhex(str)# return a2b_hex(str)
4、bytes转十六进制字符串
''' bytes to hex string eg: b'\x01#Eg\x89\xab\xcd\xef\x01#Eg\x89\xab\xcd\xef' '01 23 45 67 89 AB CD EF 01 23 45 67 89 AB CD EF' ''' def bytesToHexString(bs):# hex_str = ''# for item in bs:# hex_str += str(hex(item))[2:].zfill(2).upper() + " "# return hex_strreturn ''.join(['%02X ' % b for b in bs])
总结
以上是生活随笔为你收集整理的Python3bytes、hex、字符串之间相互转换的全部内容,希望文章能够帮你解决所遇到的问题。
- 上一篇: CentOS搭建安装SVN
- 下一篇: python netifaces模块 获