python 字符串转16进制数字

时间:2024-03-19 09:44:12

1 原始文件中的字符串

python 字符串转16进制数字


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 运行程序报错

python 字符串转16进制数字

python 字符串转16进制数字


4 对字符串进行binascii转换

python 字符串转16进制数字

5 字符串转为整型正常

python 字符串转16进制数字

原字符串为: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