Skip to content

Instantly share code, notes, and snippets.

@endolith
Last active November 27, 2023 16:06
Show Gist options
  • Save endolith/147203 to your computer and use it in GitHub Desktop.
Save endolith/147203 to your computer and use it in GitHub Desktop.
PonyProg2000: Flip bit order in a binary file

It's been a long time since I used this, and I don't remember its purpose. I think it's for writing a binary file to an EEPROM, when the chip reading that EEPROM expects the bits in reversed order.

flip_bits.py can be used on a file directly, as well, though in the context of the script it just operates on temporary files:

python flip_bits.py infile outfile

I'm sure this could be done with a very simple C command line tool instead. But hey, it works.

#------ START --------
# PonyProg2000 script to flip the bit order of the bytes in
# a binary file before writing to an EEPROM
#
# Save data
SAVE-ALL ~tmpnormal.bin bin
# Flip bits of every byte
CALL "C:\Python37\python flip_bits.py ~tmpnormal.bin ~tmpflipped.bin"
# Reload data
LOAD-ALL ~tmpflipped.bin bin
#------- END ---------
"""
Read in a binary file and flip the bit ordering of all the bytes (while
keeping the byte order the same).
Usage:
python flip_bits.py infile outfile
"""
import sys
def flip_bits(b):
"""
Reverse the bits of byte `b`. `b` must be an int in the range [0, 255]
From https://stackoverflow.com/a/2602885/125507
"""
b = (b & 0xF0) >> 4 | (b & 0x0F) << 4
b = (b & 0xCC) >> 2 | (b & 0x33) << 2
b = (b & 0xAA) >> 1 | (b & 0x55) << 1
return b
def test_flip_bits():
for n in range(256):
assert(f'{n:>08b}'[::-1] == f'{flip_bits(n):>08b}')
# TODO: There are more efficient ways to process files 1 byte at a time:
# https://stackoverflow.com/a/59013806/125507
fin = open(sys.argv[1], 'rb')
fout = open(sys.argv[2], 'wb')
while True:
byte = fin.read(1)
# Quit at end of file
if byte == b'':
break
# Flip bits
flipped = flip_bits(byte[0])
# Write flipped int to output file
fout.write(bytes((flipped,)))
fin.close()
fout.close()
@bootleg714
Copy link

Hi,

Thanks for the reply! I'm looking to flip the bit ordering of all the bytes of a PC Engine game so it can be used on an EEPROM in an American System. There was a YouTuber that used this Python script to do it. From what I can tell PonyProg has a tab where you can run a PonyProg script. Your PonyProg script references your Python scrip but all if it is completely foreign to me lol.

I appreciate you taking the time to reply. Any help is appreciated.

@endolith
Copy link
Author

@bootleg714 I updated the script to Python 3 and updated the readme

@bootleg714
Copy link

You're an absolute legend! Thank you for taking the time to help me out! Enjoy your holidays!

@pinballjim
Copy link

bootleg714 - any details on how you did this? Or a link to the youtube video? I'm attempting to run TG16 roms on a PCE EPROM cartridge.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment