python3 bytes與hex字符串互轉


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])


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM