Python3 正常顯示出十六進位制(坑人不淺)

Robin_Pi發表於2020-12-25

Python3 自動轉Unicode有時候真的是很煩人啊!!

直接上方法

input_data =  b'WAV\x04\xbc\x04\x00RR'

def print_hex(bytes):
    '''
    在Python3下列印出十六進位制位元組串
    '''
    l = [hex(int(i)) for i in bytes]
    return l 

print_hex(input_data)
['0x57', '0x41', '0x56', '0x4', '0xbc', '0x4', '0x0', '0x52', '0x52']

進階:將後面的數字補零

input_data = b'WAV\x04\xbc\x04\x00RR'

def print_hex(bytes):
    '''
    在Python3下列印出十六進位制位元組串,並補零
    '''
    l = []
    for i in bytes:
        i = hex(int(i))
#         print(i)
        if len(i) < 4:
            i = i[:2] + '0' + i[2:]
        l.append(i)
    return l

print_hex(input_data)

['0x57', '0x41', '0x56', '0x04', '0xbc', '0x04', '0x00', '0x52', '0x52']

相關文章