2 # SPDX-License-Identifier: GPL-2.0+
5 Simple tool to swap the byte endianness of a binary file.
12 """Parse command line arguments."""
13 description = "Swap endianness of given input binary and write to output binary."
15 parser = argparse.ArgumentParser(description=description)
16 parser.add_argument("input_bin", type=str, help="input binary")
17 parser.add_argument("output_bin", type=str, help="output binary")
18 parser.add_argument("-c", action="store", dest="chunk_size", type=int,
19 default=io.DEFAULT_BUFFER_SIZE, help="chunk size for reading")
21 return parser.parse_args()
23 def swap_chunk(chunk_orig):
24 """Swap byte endianness of the given chunk.
29 chunk = bytearray(chunk_orig)
31 # align to 4 bytes and pad with 0x0
32 chunk_len = len(chunk)
33 pad_len = chunk_len % 4
35 chunk += b'\x00' * (4 - pad_len)
37 chunk[0::4], chunk[1::4], chunk[2::4], chunk[3::4] =\
38 chunk[3::4], chunk[2::4], chunk[1::4], chunk[0::4]
45 with open(args.input_bin, "rb") as input_bin:
46 with open(args.output_bin, "wb") as output_bin:
48 chunk = bytearray(input_bin.read(args.chunk_size))
52 output_bin.write(swap_chunk(chunk))
54 if __name__ == '__main__':