title: Deconstructing Pokémon glitches?
body: <p>(I apologize if this is the wrong place to ask this.  I think it's definitely programming related, though if this belongs on some other site please let me know)</p>
  <p>I grew up playing Pokémon Red and Blue, games that were great fun but are somewhat notorious for having numerous exploitable glitches (for example, see <a href="http://www.youtube.com/watch?v=cYHYL8JJsFo" rel="noreferrer">this ridiculous speedrun of the game</a> that uses memory corruption to turn the item screen into a hex editor).</p>
  <p>Recently, I found an interesting speedrun of the game that uses a glitch called the &quot;ZZAZZ glitch&quot; to corrupt important memory locations and allow the player to almost immediately win the game.  According to <a href="http://tasvideos.org/2945S.html" rel="noreferrer">the author's description of the speedrun</a>, the ZZAZZ glitch works as follows:</p>
  <blockquote>
  <p>To start a Trainer battle, the game needs to load a lot of data, such as [...] the money he'll concede if defeated. When it loads the money is where things can get really ugly. For reasons that are beyond me, money is stored in a completely different manner, the game uses a data structure of three bytes and instead of converting the value to binary, it stores it in &quot;human&quot; representation. For example, $123456 would be stored as 0x123456 instead of 0x01E240, the proper conversion.</p>
  <p>[Some invalid entries in the Trainer table] point to location with invalid money data. When the game tries to perform arithmetic with these data in said structure, it goes nuts and starts overwriting huge portions of RAM. More specifically, for every block of three bytes, two of them will contain 0x9999 (the maximum amount of money a trainer could give). This pattern repeats itself many times through RAM. To see this better, I recommend pausing the video on the emulator after the ZZAZZ trainer is faced and set VBA's memory viewer to 0xD070.</p>
  </blockquote>
  <p>This analysis makes sense, but as I programmer I can't help but wonder how on earth the programmers wrote the code that would make this possible.  No approach I can think of for writing a function that converts a hexadecimal-encoded decimal number to decimal would ever start filling random blocks of memory with 0x9999 if the input wasn't a valid hexadecimal-encoded decimal number.</p>
  <p>My question is - without specifically designing the algorithm to fail this way, <strong>is there a straightforward implementation of a conversion from hexadecimal-coded decimal to decimal that could result in this sort of memory corruption when fed in an invalid value?</strong></p>
  <p>Again, if this is off-topic, my apologies.  My thoughts are that other programmers on this site may have also grown up playing this game, and it sounds like an interesting exercise in reverse-engineering to try to figure out how a glitch like this could be possible.</p>