bytes与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_str
return ‘‘.join([‘%02X ‘ % b for b in bs])
原文:https://www.cnblogs.com/gqv2009/p/12683476.html
本文介绍了如何在Python中通过defstringTobytes()、defbytesToString()、hexStringTobytes()和bytesToHexString()函数实现字符串与字节、十六进制字符串之间的转换,包括UTF-8编码和解码。
3357

被折叠的 条评论
为什么被折叠?



