endian-swap.py 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. #!/usr/bin/env python3
  2. # SPDX-License-Identifier: GPL-2.0+
  3. """
  4. Simple tool to swap the byte endianness of a binary file.
  5. """
  6. import argparse
  7. import io
  8. def parse_args():
  9. """Parse command line arguments."""
  10. description = "Swap endianness of given input binary and write to output binary."
  11. parser = argparse.ArgumentParser(description=description)
  12. parser.add_argument("input_bin", type=str, help="input binary")
  13. parser.add_argument("output_bin", type=str, help="output binary")
  14. parser.add_argument("-c", action="store", dest="chunk_size", type=int,
  15. default=io.DEFAULT_BUFFER_SIZE, help="chunk size for reading")
  16. return parser.parse_args()
  17. def swap_chunk(chunk_orig):
  18. """Swap byte endianness of the given chunk.
  19. Returns:
  20. swapped chunk
  21. """
  22. chunk = bytearray(chunk_orig)
  23. # align to 4 bytes and pad with 0x0
  24. chunk_len = len(chunk)
  25. pad_len = chunk_len % 4
  26. if pad_len > 0:
  27. chunk += b'\x00' * (4 - pad_len)
  28. chunk[0::4], chunk[1::4], chunk[2::4], chunk[3::4] =\
  29. chunk[3::4], chunk[2::4], chunk[1::4], chunk[0::4]
  30. return chunk
  31. def main():
  32. args = parse_args()
  33. with open(args.input_bin, "rb") as input_bin:
  34. with open(args.output_bin, "wb") as output_bin:
  35. while True:
  36. chunk = bytearray(input_bin.read(args.chunk_size))
  37. if not chunk:
  38. break
  39. output_bin.write(swap_chunk(chunk))
  40. if __name__ == '__main__':
  41. main()