Blockland Forums > Modification Help
Convert between characters and character indexes (Small Coding Resource)
<< < (2/2)
Space Guy:
Why is the loop necessary in the second one? I had something like these which I haven't used much yet:


--- Code: --- function base10toHex(%num)
{
  %s = "0123456789ABCDEF";
  %num = mFloor(%num);
  return getSubStr(%s,(%num - (%num % 16)) / 16,1) @ getSubStr(%s,(%num % 16),1);
}

function numToChar(%x)
{
  %num = base10toHex(%x);
  eval("%char = \"\\x" @ %num @ "\";");
  return %char;
}
--- End code ---

I didn't know that collapseEscape existed for this purpose, so this looks like it'd be shorter:

--- Code: --- function numToChar(%x)
{
  %num = base10toHex(%x);
  %char = collapseEscape("\\x" @ %num);
  return %char;
}
--- End code ---

My solution for the first one was just a few large switch statements (case "\x51": return 81; works with input charToNum("Q")) so whether that's faster than the loop or not I don't know. Incidentally a switch statement errors after about 83 cases and doesn't work.

They should both test for 16*%x + %y otherwise it's getting most of the cases wrong.
Kalphiter:
I had this from 2 years ago, and I chose the name "chr" because that's the equivalent in PHP.


--- Code: ---function dec2hex(%val) 
{
    %digits ="0123456789ABCDEF";
    %firstDigit = getSubStr(%digits, mFloor(%val/16), 1);
    %secDigit = getSubStr(%digits, %val % 16, 1);   
    return %firstDigit @ %secDigit; 
}

function chr(%num)
{
    %rand = getRandom();
    eval("$chrString["@ %rand @"] = \"\\x"@ dec2hex(%num) @"\";");
    %return = $chrString[%rand];
    $chrString[%rand] = "";
    return %return;
}
--- End code ---
The %rand is just for a random string to retrieve later, it could be made more efficient.
For example, when you convert a number to a character, you can store the number in an array with character as the index, so that you don't have to loop through everything again.
Navigation
Message Index
Previous page

Go to full version