in reply to signed bin2dec

sub sb2d{ my $b = unpack 'N', pack("B32", substr("0" x 32 . shift, -32)); $b > 2**31 ? -(1+~$b) : $b }

Examine what is said, not who speaks.
"Efficiency is intelligent laziness." -David Dunham
"Think for yourself!" - Abigail

Replies are listed 'Best First'.
Re: Re: signed bin2dec
by spurperl (Priest) on Mar 19, 2004 at 11:05 UTC
    This surely works, but unfortunately limited to 32 bit strings.

      UPDATE:Just in case there is anyone (else?) who hasn't spotted the joke.

      Variable-length, signed binary strings DO NOT MAKE ANY SENSE!!!.

      What values do the following binary strings represent?

      • 0b10

        2 or -0?

      • 0b11111111111111111111111111111111111111111111

        A big integer or -1?

      You cannot two's complement a variable number of bits without fixing the length. Yes. This post was sacarstic and should have been identified as such, but I thought it obvious.

      END UPDATE

      Okay. Try this version. It will handle up to 1023 digit binary strings. Beyond that, you'll probably need Math::BigInt

      sub sb2d{ my $n=shift; return undef unless $n =~ m[^[01]+$]; my $s=ord( $n )==49; $n=~tr[01][10] if $s; $n = eval{ no warnings; eval '0b'.$n;}; $s ? -1 * ++$n : $n }

      Update: The above is overly crude, so here is (I think) a slightly improved version. It still uses eval and requires no warnings;, but this seems to me acceptable to re-use perl's built-in binary string parser rather than role your own? It should be relatively safe unless anyone can see a way of injecting "nasty code" that uses only '0's & '1's?

      sub signedBin2Dec{ my $n=shift; return undef unless $n =~ m[^([01])[01]+$]; $n=~tr[01][10] if $1; $n = do{ no warnings; eval '0b'. $n}; $1 ? -1 * ++$n : $n }

      Examine what is said, not who speaks.
      "Efficiency is intelligent laziness." -David Dunham
      "Think for yourself!" - Abigail
        my $s=ord( $n )==49;

        Well, if I ever had any doubts that premature nano-optimization was truely evil, I certainly don't now.

        - tye