Wrote these to help with bitfeild manipulations as it is hard when tired to think in bits. binary2integer was an afterthought.
"integer c" is used to represent every bit by shifting it the bit over; multiplying it by 2 does the shift (*curses LSL for not having bitshifts*).
(binary)
10000000 * 01000000 = 01000000 (2)
01000000 * 01000000 = 00100000 (4)
00100000 * 01000000 = 00010000 (8)
00010000 * 01000000 = 00001000 (16)
00001000 * 01000000 = 00000100 (32)
00000100 * 01000000 = 00000010 (64)
00000010 * 01000000 = 00000001 (-128)
00000001 * 01000000 = 00000000 (0)
this was only an 8 bit representation. LSL is 32.
the last bit is used to represent the negative bit.
The code depends on integer arithmatic overflowing into the negative. ie (2 * 1073741824 = -214748364

and (2 * -2147483648 = 0) That is why we do a check for (c && a<0) as the negative bit is last. (If LSL ever goes to long long (64bit integers) then this code will still work as the overflow will just be at a different point.) When a>0 all we need to do is check which is bigger c or or a and if a is bigger than we contiue. finaly if we check if a==0 so we can run the loop once as to return "0".
Then for checking the value of the bit in that possition we just and c & a, which will return c if there is a 1 and 0 if nothing. Since compairing it to zero is the fastest way for checking that is what we do.
-----
binary2integer we do something similar. We still have c and it increments in the same way. We read the string 1 letter at a time and see if it "1" this test returns a 1 or a 0. We multiply the result of the test by c then Or it to d (same effect as adding it but a bit faster)
-----
Issues:
Since LSL is 32 bit if you try to feed a longer binary number to binary2integer the extra bits will be lost as C will overflow into 0. We do a check for this as it's just a waste of CPU time to continue.
binary2integer only does a check for "1" so this function will try and parse any string and return a number.
-----
Optimization:
If your worried about CPU time then you should use this version of integer2binary
string integer2binary(integer a)
{
integer c;
string d;
if (a<0)
for (c=1;c;c*=2)
d+=(string)((a&c)!=0);
else if (a)
for (c=1;c<=a && c;c*=2)
d+=(string)((a&c)!=0);
else
d="0";
return d;
}