1. 程式人生 > >python 字串轉16進位制數字

python 字串轉16進位制數字

1 原始檔案中的字串


2 讀取檔案字串

從檔案中讀取2個位元組,程式碼如下:

def print_hex_str(str1):
    print len(str1)
    print str1
    print int(str1, 16)
    for i in str1:
        print "--------"
        print('%#X' % ord(i))
        print('%d' % ord(i))

def des_ecb_decrypt_from_file(srcfile, dstfile, key):
    fsrc = open(srcfile, 'rb')
    if not fsrc:
        print "fsrc open failed!"
    fdst = open(dstfile, 'wb')
    if not fdst:

        print "fdst open failed!"

    datalen = fsrc.read(2)
    print type(datalen)
    print len(datalen)

    print_hex_str(datalen)

3 執行程式報錯



4 對字串進行binascii轉換


5 字串轉為整型正常


原字串為:0X000X58

轉換後的字串為:0058

6 binascii分析

binascii.b2a_hex(data) 字串轉16進位制字串binascii.hexlify(data)

Return the hexadecimal representation of the binary data

. Every byte of data is converted into the corresponding 2-digit hex representation. The resulting string is therefore twice as long as the length of data.

官方網址:https://docs.python.org/2/library/binascii.html

7 參考資料

(1) https://blog.csdn.net/penny_hardaway/article/details/45046643

(2) https://www.cnblogs.com/LarryGen/p/5088144.html