http://www.perlmonks.org?node_id=295453

Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Are there built in functions (or a module) to provide facilities for simple binary math (eg, accepting two strings representing bitstrings as arguments and returning a bitstring with the result of addition/subtraction) ?

Replies are listed 'Best First'.
Re: Binary Math?
by BrowserUk (Patriarch) on Sep 30, 2003 at 22:07 UTC

    I'm not aware of any modules for this, but I never looked as perl makes it so easy to this yourself.

    #! perl -slw use strict; sub b2n{ eval '0b'. $_[0] } sub n2b{ sprintf '%b', $_[0] } my( $bs1, $bs2 ) = ( '0100100100101', '1010101010100' ); print "$bs1 + $bs2 = ", n2b( b2n( $bs1 ) + b2n( $bs2 ) ); __END__ P:\test>295453 0100100100101 + 1010101010100 = 1111001111001

    If your bitstrings are longer than 32 bits (or 64 if your lucky enough to be using a 64-bit platform) then you might need something more elaborate.


    Examine what is said, not who speaks.
    "Efficiency is intelligent laziness." -David Dunham
    "When I'm working on a problem, I never think about beauty. I think only how to solve the problem. But when I have finished, if the solution is not beautiful, I know it is wrong." -Richard Buckminster Fuller
    If I understand your problem, I can solve it! Of course, the same can be said for you.

Re: Binary Math?
by athomason (Curate) on Sep 30, 2003 at 22:01 UTC
    Use oct to go from bitstrings to numbers and sprintf to go from a number to a bitstring. As for the math, the usual operators work once you've done the conversion.
    #!/usr/bin/perl use strict; use warnings; my $bitstring1 = shift @ARGV || '10010010111'; my $bitstring2 = shift @ARGV || '01101011010'; my $number1 = oct "0b$bitstring1"; my $number2 = oct "0b$bitstring2"; printf "%s + %s = %b\n", $bitstring1, $bitstring2, $number1 + $number2 +;

    Update

    As BrowserUK mentioned, this will only get you as far as your platform's integer types allow. Fortunately, Math::BigInt also accepts the '0b' prefix for input and has the as_bin method for output, and has replacements for oodles of math operations.

Re: Binary Math?
by BUU (Prior) on Sep 30, 2003 at 21:57 UTC
    Uh, are you looking for the binary operators  | & ^ defined in perlop?