Tuesday, 20 December 2011

String to ByteArray

In Bug Tunnel Defense all levels (called missions in-game) are stored as Strings. This includes the built in levels, levels stored on the user's machine that they've created, and levels stored online in GamerSafe's LevelVault and Kongregate's shared content system. Kongregate also uses Strings, so was very straightforward. But LevelVault requires data stored in a ByteArray, so I needed to convert Strings to ByteArray.



I did not find this documented anywhere but it turned out to be very straightforward. The code to convert to ByteArray is


function SaveLevel(sLev:String):void {
    var ba:ByteArray, iChar:int;
    for (iChar = 0; iChar < sLev.length; iChar++) {
        ba.writeByte(sLev.charCodeAt(iChar));
    }
    gsf.levelVaultCreateLevel(ba);
}


While the code to extract the String from the ByteArray is even simpler:


function GetLevel(iLevelID:int):String {
    var ba:ByteArray;
    ba = gsf.levelVaultGetLevelData(iLevelID);
    return ba.toString();
}


'gsf' is a copy of the GamerSafe object. In practice a lot more happens than this, but the above code includes all the code concerned with ByteArrays.

No comments:

Post a Comment