1#!/usr/bin/env python3
2# SPDX-License-Identifier: GPL-2.0+
3
4"""
5Simple tool to swap the byte endianness of a binary file.
6"""
7
8import argparse
9import io
10
11def parse_args():
12    """Parse command line arguments."""
13    description = "Swap endianness of given input binary and write to output binary."
14
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")
20
21    return parser.parse_args()
22
23def swap_chunk(chunk_orig):
24    """Swap byte endianness of the given chunk.
25
26    Returns:
27        swapped chunk
28    """
29    chunk = bytearray(chunk_orig)
30
31    # align to 4 bytes and pad with 0x0
32    chunk_len = len(chunk)
33    pad_len = chunk_len % 4
34    if pad_len > 0:
35        chunk += b'\x00' * (4 - pad_len)
36
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]
39
40    return chunk
41
42def main():
43    args = parse_args()
44
45    with open(args.input_bin, "rb") as input_bin:
46        with open(args.output_bin, "wb") as output_bin:
47            while True:
48                chunk = bytearray(input_bin.read(args.chunk_size))
49                if not chunk:
50                    break
51
52                output_bin.write(swap_chunk(chunk))
53
54if __name__ == '__main__':
55    main()
56