Python之bin2rev

本文介绍了一个Python脚本,用于将bin文件中的数据从一种字节序转换为另一种字节序。通过指定文件名及转换包大小,可以轻松完成转换任务。

使用Python将bin文件进行大小端转换:

import os
import sys
import time
import binascii
from struct import *

#FILE='test.bin'
FILE=sys.argv[1]
PACK_SIZE=4

(filename,ext) = os.path.splitext(FILE)
file_to_write = filename+'.rev'+'.bin'

def bin2rev():
    with open(FILE, 'rb') as fp_read:
        cnt = 0
        fp_write = open(file_to_write, 'wb')
        while 1:
            cont = fp_read.read(PACK_SIZE)
            if len(cont) == PACK_SIZE:
                cnt = cnt + PACK_SIZE
                for i in range(0, len(cont)):
                    tmp = pack('B' ,cont[PACK_SIZE - i - 1])
                    fp_write.write(tmp)
            else:
                fsize = os.path.getsize(FILE)
                if cnt == fsize:
                    print("Success!")
                else:
                    print("Failed!")
                break
        fp_write.close()

if len(sys.argv) > 2:
    PACK_SIZE = ord(sys.argv[2]) - 48
    if PACK_SIZE % 4 != 0:
        print("Pack size error!")
        time.sleep(1)
bin2rev()
time.sleep(1)
#os.system("pause")

将xxx.bin文件拖拽到bin2rev.py上或使用bat批处理执行带参数的python脚本即可得到大小端转换后的xxx.rev.bin文件

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值