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?
2 or -0?
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 }
In reply to Re: Re: Re: signed bin2dec
by BrowserUk
in thread signed bin2dec
by spurperl
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |