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

In reply to Re: Re: Re: signed bin2dec by BrowserUk
in thread signed bin2dec by spurperl

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.