Re: Can this code go faster?

From: Date: Fri, 29 Apr 2005 10:45:11 +0000
Subject: Re: Can this code go faster?
References: 1 2  Groups: php.general 
Request: Send a blank email to php-general+get-214195@lists.php.net to get a copy of this message
Just a couple of comments about those 0xffff.. and 1111111111 in my post. (By the way, i haven't looked to closely on speed even if the OP asked for that, i was unsure on how he was coding his numbers). rolfostvikjobb@yahoo.no (Rolf Østvik) wrote in news:Xns9644DC6E96EBBrolfostvikjobbyahoon@216.92.131.4: > 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. > > 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; if the input is a 8 bit signed binary string then bit 7 determine the sign. 0xffffff00 will then make this to an 32 signed integer > > return $val; > } > > function bin2int ($bin) { > if (substr($bin,0,1) == 1) { > // NEGATIVE > $val = bindec(substr("11111111111111111111111111111111" > .$bin,-32)); bindec returns a 32 bit signed integer, i just make sure that the leftmost bits in the 32 character long string are 1 if the leftmost bit in the original string is 1. > } else { > // POSITIVE > $val = bindec($bin); > } > return $val; > } > -- Rolf

« previous php.general (#214195) next »