Pyhton 学习笔记之 bin2hex & hex2bin

来源:互联网 发布:linux设置用户密码 编辑:程序博客网 时间:2024/05/18 22:17
# -*- coding: cp936 -*-import sysimport 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) 可以查看。