in reply to Re: Re: signed bin2dec
in thread signed bin2dec

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?

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

Replies are listed 'Best First'.
Re^4: signed bin2dec (argh!!!)
by tye (Sage) on Mar 19, 2004 at 16:22 UTC
    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        

      OooW. Does that make it go faster? And I thought I was just being lazy :)


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