|
Posted by Rolf Ψstvik on 04/29/05 13:45
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
[Back to original message]
|