I need to convert a binary number of arbitrary length to a signed integer.
This is how I'm doing it now:
CODE -------- function bin2int ($bin) { if (substr($bin,0,1) == 1) { $val = 0 - bindec(substr($bin,1)); // NEGATIVE } else { $val = bindec(substr($bin,1)); // POSITIVE } }
echo bin2int("00001101").'<br />'; echo bin2int("10001101");
OUTPUT -------- 13 -13
As you can see, if the most-significant bit is 1, then the rest of the value is negative. If the first bit is 0, then the rest is positive. Is there a better, faster (execution-wise) way of doing this? Maybe a more built-in function of PHP I missed? It's something that my script will be doing thousands of times, so I am concerned about speed.
Thanks!
...Rene
-- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php