python 工具 二进制文件处理之——大小端变换

大端换小端 16位:

import struct
import sys


# main body
if sys.argv.__len__() > 1:
# 参数获取
src_file = sys.argv[1]
else:
# 文本输入
src_file = input("Source Bin Path: ")

dst_file = src_file[0:(src_file.__len__()-2)]
dst_i_file = dst_file
dst_file += "_le.bin"
dst_i_file += ".i"
print("Source file: {0}\nTarget File: {1}\n\t{2}".format(src_file, dst_file, dst_i_file))

sf = open(src_file, "rb")
df = open(dst_file, "wb")
dif = open(dst_i_file, "w")

buf_tmp = [b'0' for x in range(0, 2)]
contents = sf.read()
buf_size = contents.__len__()
extra_size = (buf_size % 2)
if extra_size > 0:
buf_size += (2 - extra_size)
contents = contents + b'0000'

for i in range(0, buf_size, 2):
buf_tmp[1] = contents[i]
buf_tmp[0] = contents[i+1]

if (i > 0) and ((i % 16) == 0):
dif.write("\n")
for j in range(0, 2):
dif.write(str.format("0x%02x," % buf_tmp[j]))

# pack into bytes flow
tmp_bytes = struct.pack("2B", buf_tmp[0], buf_tmp[1])
df.write(tmp_bytes)

dif.close()
sf.close()
df.close()

print("Convert Completed!")

大端换小端 32位

import struct
import sys


# main body
if sys.argv.__len__() > 1:
# 参数获取
src_file = sys.argv[1]
else:
# 文本输入
src_file = input("Source Bin Path: ")

dst_file = src_file[0:(src_file.__len__()-4)]
dst_i_file = dst_file
dst_file += "_le.bin"
dst_i_file += ".i"
print("Source file: {0}\nTarget File: {1}\n\t{2}".format(src_file, dst_file, dst_i_file))

sf = open(src_file, "rb")
df = open(dst_file, "wb")
dif = open(dst_i_file, "w")

buf_tmp = [b'0' for x in range(0, 4)]
contents = sf.read()
buf_size = contents.__len__()
extra_size = (buf_size % 4)
if extra_size > 0:
buf_size += (4 - extra_size)
contents = contents + b'0000'

for i in range(0, buf_size, 4):
buf_tmp[3] = contents[i]
buf_tmp[2] = contents[i+1]
buf_tmp[1] = contents[i+2]
buf_tmp[0] = contents[i+3]

if (i > 0) and ((i % 16) == 0):
dif.write("\n")
for j in range(0, 4):
dif.write(str.format("0x%02x," % buf_tmp[j]))

# pack into bytes flow
tmp_bytes = struct.pack("4B", buf_tmp[0], buf_tmp[1], buf_tmp[2], buf_tmp[3])
df.write(tmp_bytes)

dif.close()
sf.close()
df.close()

print("Convert Completed!")

猜你喜欢

转载自www.cnblogs.com/dzzy/p/9082869.html