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

  • 1
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值