Author Topic: [Resource] Better ASCII table lookup  (Read 1673 times)

This old thing is probably one of the worst pieces of code I've ever written. Here's a version that's actually good:

function chr(%i)
{
    return $_byte_map[%i];
}

function ord(%c)
{
    return 1 + strpos($_byte_list, %c);
}

if ($_byte_list $= "")
{
    for ($_i = 1; $_i < 256; $_i++)
    {
        $_byte_map[$_i] = collapseEscape("\\x" @
            getSubStr("0123456789abcdef", $_i >> 4, 1) @
            getSubStr("0123456789abcdef", $_i & 15, 1));
        $_byte_list = $_byte_list @ $_byte_map[$_i];
    }
}




This is just about on the limit of how fast this can be done in TS.
Behaves correctly with NULL. Passing multi-character strings to ord will result in undefined behavior.
Also doubles as binary conversion of course, as TS strings are by default simple byte arrays that can't store NULL.
« Last Edit: December 31, 2014, 10:22:17 AM by portify »

To be specific:
   ord(c) returns the decimal value corresponding to byte c (or ASCII character).
   chr(i) returns the byte (or ASCII character) corresponding to decimal value i.

This means that, for example, you can echo every character supported by Blockland with:
   for (%i = 1; %i < 256; %i++)
        echo(%i SPC "=" SPC chr(%i));


Or convert string %s to ASCII codepoints with:

    %length = strlen(%s);
    for (%i = 0; %i < %length; %i++)
    {
        %char = getSubStr(%s, %i, 1);
        echo("%s[" @ %i @ "] = " @ %char @ " => " @ ord(%char));
    }

Very useful, thanks. Make sure this gets added to the Resources topic.