You are here: Re: Can this code go faster? « PHP « IT news, forums, messages
Re: Can this code go faster?

Posted by Rolf Ψstvik on 10/12/10 11:14

m5@renefournier.com (Renι Fournier) wrote in
news:49fe5cee6cb5560b525fe3a26fdbbba1@renefournier.com:

> 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.

If this is what you want then your numeric representation of negative
numbers is not standard. In that case your function is as good as you can
get.

This is the standard two's complement representation:
"00001101" is 13
"11110010" is -13
"10001101" is -115

You specify the most-significant bit as sign bit, and that you can have a
arbitrary lenght string representing a binary number.
Then "010" will be different than "10", is that correct?


If you on the other hand know that the string should represent an 8 bit in
two's complement then this could work:

function bin2int ($bin) {
$a = bindec($bin);

$val = ($a | 0x80) ? (0xffffff00 | $a) : $a;

return $val;
}

// or by using if instead of ? and :
//function bin2int ($bin) {
// $a = bindec($bin);
// if ( $a | 0x80) {
// $val = (0xffffff00 | $a);
// } else {
// $val =$a;
// }
//
// return $val;
//}

If the string represent a 16 bit number use
$val = ($ | 0x8000) ? (0xffff0000 | $a) : $a;

If the string represent a 32 bit number use only bindec

If you still want
- a leading 1 to represent a negative number,
- and that the string can have arbitrary lenght,
- but you want correct two's complement representation
then we need something different, e.g:

function bin2int ($bin) {
if (substr($bin,0,1) == 1) {
// NEGATIVE
$val = bindec(substr("11111111111111111111111111111111".$bin,-32));
} else {
// POSITIVE
$val = bindec($bin);
}
return $val;
}

--
Rolf

 

Navigation:

[Reply to this message]


УдалСнная Ρ€Π°Π±ΠΎΡ‚Π° для программистов  •  Как Π·Π°Ρ€Π°Π±ΠΎΡ‚Π°Ρ‚ΡŒ Π½Π° Google AdSense  •  England, UK  •  ΡΡ‚Π°Ρ‚ΡŒΠΈ Π½Π° английском  •  PHP MySQL CMS Apache Oscommerce  •  Online Business Knowledge Base  •  DVD MP3 AVI MP4 players codecs conversion help
Home  •  Search  •  Site Map  •  Set as Homepage  •  Add to Favourites

Copyright © 2005-2006 Powered by Custom PHP Programming

Π‘Π°ΠΉΡ‚ ΠΈΠ·Π³ΠΎΡ‚ΠΎΠ²Π»Π΅Π½ Π² Π‘Ρ‚ΡƒΠ΄ΠΈΠΈ Π’Π°Π»Π΅Π½Ρ‚ΠΈΠ½Π° ΠŸΠ΅Ρ‚Ρ€ΡƒΡ‡Π΅ΠΊΠ°
ΠΈΠ·Π³ΠΎΡ‚ΠΎΠ²Π»Π΅Π½ΠΈΠ΅ ΠΈ ΠΏΠΎΠ΄Π΄Π΅Ρ€ΠΆΠΊΠ° Π²Π΅Π±-сайтов, Ρ€Π°Π·Ρ€Π°Π±ΠΎΡ‚ΠΊΠ° ΠΏΡ€ΠΎΠ³Ρ€Π°ΠΌΠΌΠ½ΠΎΠ³ΠΎ обСспСчСния, поисковая оптимизация