Difference between revisions of "BinaryDecimalConverter"
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.) |
Omei Qunhua (talk | contribs) (shorter decToBin) |
||
Line 26: | Line 26: | ||
Greets from Soundless :) | 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. | |||
<lsl> | |||
string decToBin(integer val) | |||
{ | |||
string binary; | |||
do | |||
binary = (string) (val & 1) + binary; | |||
while (val /= 2); | |||
return binary; | |||
} | |||
</lsl> | |||
((Omei)) |
Revision as of 05:33, 19 January 2013
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 : <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 :)
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.
<lsl> string decToBin(integer val) {
string binary; do binary = (string) (val & 1) + binary; while (val /= 2); return binary;
} </lsl> ((Omei))