Skip to content

Instantly share code, notes, and snippets.

@obskyr
Last active March 9, 2018 13:51
Show Gist options
  • Save obskyr/c8d87e0614140da668c1bbfc48ab5081 to your computer and use it in GitHub Desktop.
Save obskyr/c8d87e0614140da668c1bbfc48ab5081 to your computer and use it in GitHub Desktop.
A Python script to convert Game Boy memory addresses between absolute and banked forms.
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Convert Game Boy addresses between absolute and banked forms.
from __future__ import print_function
from __future__ import unicode_literals
import sys
def to_banked(absolute_address):
absolute_address = int(absolute_address, 16)
bank, address = absolute_address // 0x4000, absolute_address % 0x4000
if bank != 0:
address += 0x4000
return "{:02X}:{:04X}".format(bank, address)
def to_absolute(banked_address):
bank, address = [int(n, 16) for n in banked_address.split(':', 1)]
memory_start = 0 if bank == 0 else 0x4000
if not memory_start <= address < memory_start + 0x4000:
raise ValueError("Memory address not within bank.")
return "{:06X}".format(bank * 0x4000 + address - memory_start)
def cross_convert(address):
if ':' in address:
return to_absolute(address)
else:
return to_banked(address)
if __name__ == '__main__':
if not sys.argv[1:]:
print("Usage: banksy [addresses...]")
print("For example: banksy BC160 6F:430A")
else:
for address in sys.argv[1:]:
try:
print(cross_convert(address))
except ValueError:
print("[invalid address]")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment