Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister
 
PerlMonks  

Re: Binary Math?

by athomason (Curate)
on Sep 30, 2003 at 22:01 UTC ( #295459=note: print w/ replies, xml ) Need Help??


in reply to Binary Math?

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.


Comment on Re: Binary Math?
Select or Download Code

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://295459]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others browsing the Monastery: (16)
As of 2015-07-30 13:20 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (271 votes), past polls