Difference between revisions of "BinaryDecimalConverter"

From Second Life Wiki
Jump to navigation Jump to search
(Won't crash on negative numbers now. I'm wondering if 'binary = (string)(val & 1) + binary' would be faster than the if-else block.)
Line 1: Line 1:
{{LSL Header}}
{{LSL Header}}
The next function converts a binary value to a decimal number. Works +/- 5 times faster than [[Base2Dec]] :
The next function converts a binary value to a decimal number. Works +/- 5 times faster than [[Base2Dec]] :
<lsl>
<lsl>integer binToDec(string val)
integer binToDec(string val)
{
{
     integer dec;
     integer dec = 0;
   
     integer i = ~llStringLength(val);
     integer i = -llStringLength(val);
     while(++i)
   
     while(++i < 0)
    {
         dec = (dec << 1) + (integer)llGetSubString(val, i, i);
         dec = (dec << 1) + (integer)llGetSubString(val, i, i);
    }
     return dec;
     return dec;
}
}</lsl>
</lsl>


This one converts a decimal to a binary value:
This one converts a decimal to a binary value:


<lsl>
<lsl>string decToBin(integer val)
string decToBin(integer val)
{
{
     string binary;
     string binary = (string)(val & 1);
     integer i = val;
     for(val = ((val >> 1) & 0x7FFFffff); val; val = (val >> 1))
    while (i)
     {
     {
         if (i % 2)
         if (val & 1)
             binary = "1" + binary;
             binary = "1" + binary;
         else
         else
             binary = "0" + binary;
             binary = "0" + binary;
       
        i = i >> 1;
     }
     }
     return binary;
     return binary;
}
}</lsl>
</lsl>


Greets from Soundless :)
Greets from Soundless :)

Revision as of 15:03, 18 October 2009

The next function converts a binary value to a decimal number. Works +/- 5 times faster than Base2Dec : <lsl>integer binToDec(string val) {

   integer dec = 0;
   integer i = ~llStringLength(val);
   while(++i)
       dec = (dec << 1) + (integer)llGetSubString(val, i, i);
   return dec;

}</lsl>

This one converts a decimal to a binary value:

<lsl>string decToBin(integer val) {

   string binary = (string)(val & 1);
   for(val = ((val >> 1) & 0x7FFFffff); val; val = (val >> 1))
   {
       if (val & 1)
           binary = "1" + binary;
       else
           binary = "0" + binary;
   }
   return binary;

}</lsl>

Greets from Soundless :)