So I'm working on a project in which I need to be able to store and work with numbers that exceed the integer size limit. To try and break-out of the integer limitations, I have written a script that adds two strings instead: string str1 = "123456789";
string str2 = "123456789123456";
string StringPad(string source, integer number)
{
string str = "";
integer x;
for (x = 0; x < number; x++)
{
str += "0";
}
return str + source;
}
string StringLeftTrim(string source)
{
integer x = 0;
string str = llGetSubString(source, 0, 0);
while (str == "0")
{
str = llGetSubString(source, x, x);
++x;
}
return llGetSubString(source, x - 1, -1);
}
string StringReverse(string source)
{
string str;
integer x;
integer len = llStringLength(source);
for (x = 1; x <= len; x++)
str += llGetSubString(source, len - x, len - x);
return str;
}
string BigIntAdd(string st1, string st2)
{
integer carry = 0;
integer length1 = llStringLength(st1);
integer length2 = llStringLength(st2);
string final = "";
integer dif;
integer i;
llSay(0,st1+"+"+st2);
if(length1 < length2)
{
dif = length2-length1;
st1 = StringPad(st1,dif);
}
else if(length1 > length2)
{
dif = length1-length2;
st2 = StringPad(st2,dif);
}
else if(length1 == length2)
{
dif = length1;
}
length1 = llStringLength(st1);
length2 = llStringLength(st2);
do
{
integer i1 = (integer)llGetSubString(st1,length1,length1);
integer i2 = (integer)llGetSubString(st2,length2,length2);
integer i3 = i1 + i2 + carry;
if(i3 > 9)
{
carry = 1;
i3 = i3 - 10;
}
else
{
carry = 0;
}
final+=(string)i3;
length1--;
length2--;
}
while(length1 >= 0);
//final+=(string)carry;
final = StringLeftTrim(final);
final = StringReverse(final);
final+=(string)carry;
//final
return final;
}
default
{
state_entry()
{
llListen(123,"",llGetOwner(),"");
}
touch_start(integer total_number)
{
llSay(0, BigIntAdd(str1,str2));
}
listen(integer ch, string n, key id, string msg)
{
list tmp = llParseString2List(msg,["+"],[]);
llSay(0,BigIntAdd(llList2String(tmp,0),llList2String(tmp,1)));
}
} There are however, a few issues. The 'carry' integer adds an additional 0 onto the end of the final string when it is not needed, but not when the number actually does end on 0 (from what i've seen.)Adding two numbers that round up can cause interesting results. (5+5, 555+55555055, 999+999 etc)I'm sure this could be optimised further.If anyone could enlighten me as to why this is happening, or have suggestions for optimisation I'd greatly appreciate it!