Difference between revisions of "BinaryDecimalConverter"
Jump to navigation
Jump to search
(2 functions to do decimal/binary conversions) |
m (<lsl> tag to <source>) |
||
(4 intermediate revisions by 3 users not shown) | |||
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]] : | ||
< | <source lang="lsl2">integer binToDec(string val) | ||
integer binToDec(string val) | |||
{ | { | ||
integer dec; | integer dec = 0; | ||
integer i = ~llStringLength(val); | |||
integer i = | while(++i) | ||
while(++i | |||
dec = (dec << 1) + (integer)llGetSubString(val, i, i); | dec = (dec << 1) + (integer)llGetSubString(val, i, i); | ||
return dec; | return dec; | ||
} | }</source> | ||
</ | |||
This one converts a decimal to a binary value: | This one converts a decimal to a binary value: | ||
< | <source lang="lsl2">string decToBin(integer val) | ||
string | |||
{ | { | ||
string binary; | string binary = (string)(val & 1); | ||
for(val = ((val >> 1) & 0x7FFFffff); val; val = (val >> 1)) | |||
{ | { | ||
if ( | if (val & 1) | ||
binary = "1" + binary; | binary = "1" + binary; | ||
else | else | ||
binary = "0" + binary; | binary = "0" + binary; | ||
} | } | ||
return binary; | |||
}</source> | |||
Greets from Soundless :) | |||
This version of decToBin doesn't crash on negatives, is shorter source code and about 50 bytes shorter in Mono bytecode than the original, but sadly about 50% slower. << and >> are expensive on bytecode. | |||
<source lang="lsl2"> | |||
string decToBin(integer val) | |||
{ | |||
string binary; | |||
do | |||
binary = (string) (val & 1) + binary; | |||
while (val /= 2); | |||
return binary; | return binary; | ||
} | } | ||
</ | </source> | ||
((Omei)) |
Latest revision as of 18:27, 24 January 2015
LSL Portal | Functions | Events | Types | Operators | Constants | Flow Control | Script Library | Categorized Library | Tutorials |
The next function converts a binary value to a decimal number. Works +/- 5 times faster than Base2Dec :
integer binToDec(string val)
{
integer dec = 0;
integer i = ~llStringLength(val);
while(++i)
dec = (dec << 1) + (integer)llGetSubString(val, i, i);
return dec;
}
This one converts a decimal to a binary value:
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;
}
Greets from Soundless :)
This version of decToBin doesn't crash on negatives, is shorter source code and about 50 bytes shorter in Mono bytecode than the original, but sadly about 50% slower. << and >> are expensive on bytecode.
string decToBin(integer val)
{
string binary;
do
binary = (string) (val & 1) + binary;
while (val /= 2);
return binary;
}
((Omei))