LSL Wiki Mirror 10-5-2006: ExampleNumberConversion

HomePage :: PageIndex :: RecentChanges :: RecentlyCommented :: UserSettings ::
These two functions allow conversion between a string of any charset (like hexadecimal, octal, etc.) and integer. Simply adjust the charset variables to change your charset. You could even do something like an octal system that uses the letters A-H instead of 0-7.

string  charset = "0123456789abcdef";

integer chr2int(string chr) { // convert unsigned charset to integer
    integer base = llStringLength(charset);
    integer i = -llStringLength(chr);
    integer j = 0;
    while(i)
        j = (j * base) + llSubStringIndex(charset, llGetSubString(chr, i, i++));
    return j;
}

string int2chr(integer int) { // convert integer to unsigned charset
    integer base = llStringLength(charset);
    string  out;
    integer j;
    if(int < 0) {
        j = ((0x7FFFFFFF & int) % base) - (0x80000000 % base);
        integer k = j % base;
        int = (j / base) + ((0x7FFFFFFF & int) / base) - (0x80000000 / base);
        out = llGetSubString(charset, k, k);
    }
    do
        out = llGetSubString(charset, j = int % base, j) + out;
    while(int /= base);
    return out;
}

default {
    state_entry() {
        integer a = 0x80000000;
        string hex = int2chr(a);
        llOwnerSay( llList2CSV([a, hex, chr2int(hex)]));
    }
}


Examples
There are 7 comments on this page. [Display comments/form]