Pyhton 学习笔记之 bin2hex & hex2bin

# -*- coding: cp936 -*-
import sys
import binascii 
def print_usage():
    print "usage example : command inputfile  outputfile "

def bin2hex():
    MAX_FILE_NUM = 3
    argc = len(sys.argv)
    argv = sys.argv
    BUFF_SIZE = 0x1000

    if argc < MAX_FILE_NUM:
        print 'argc < ',MAX_FILE_NUM
    else:
        try:
            fp_r = open(str(sys.argv[1]),'rb')
            fp_w = open(str(sys.argv[2]),'wb+')
        except IOError:
            print sys.argv[1],"IOError "
            return
        hex_byte_count = 0
        lst = ["%02x " % i for i in range(0x100)]
        while True:
            buf = fp_r.read(BUFF_SIZE)
            buf_len = len(buf)
            #rint buf_len
            if buf_len > 0 :
                s_hex = ''
                for i in range(buf_len):
                    if (hex_byte_count % 0x20) == 0:
                        if hex_byte_count == 0:
                            s_hex +=  "%08x " % (hex_byte_count)
                        else:
                            s_hex +=  "\n%08x " % (hex_byte_count)
                    s_hex += lst[ord(buf[i])];
                    hex_byte_count += 1
                fp_w.write(s_hex)
            else:
                break

        fp_r.close()
        fp_w.close()
def hex2bin():
    MAX_FILE_NUM = 3

    if len(sys.argv) < MAX_FILE_NUM:
        print 'argc < ',MAX_FILE_NUM
    else:
        try:
            fp_r = open(str(sys.argv[1]),'rb')
            fp_w = open(str(sys.argv[2]),'wb+')
        except IOError:
            print sys.argv[1],"IOError "
            return

        while True:
            w_buf = ""
            buf = fp_r.readline()
            buf_len = len(buf)
            if buf_len > 0 :
                for e in buf.strip().split(): 
                    if len(e) == 2 :
                        s_bin = binascii.a2b_hex(e)
                        w_buf += s_bin
                    else:
                        pass
                fp_w.write(w_buf)
            else:
                break
        fp_r.close()

if __name__ == '__main__':
    hex2bin()
    #bin2hex()

1、尝试在win7 下使用 sys.stdout.write(hex) 会导致 bin2hex 输出的文件里面多出0d 不知为何。
2、binascii.a2b_hex 功能需要导入模块binascii模块。这个 a2b_hex 函数功能是将字符串 “42” 转化为16进制的 0x42 。由函数名字 a2b_hex 可以猜测a是ascii缩写,b 是 Byte缩写,hex 是 hexadecimal 缩写,‘2’是 英文 “to” 的形声表达。binascii 模块的其他功能可以通过名字去猜测验证。具体的方法 help(binascii) 可以查看。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值