And, just for fun, here's a very slow pure perl version that does not depend on arithmetic ops.
#!perl use warnings; use strict; # arithmetic operations on (nonegative) binary numbers sub addbin0 { my($a,$b) = @_; $a || $b ? ( chop($a) ? (chop($b) ? addbin1($a, $b) . "0" : addbin0($a, $b) . "1") : (chop($b) ? addbin0($a, $b) . "1" : addbin0($a, $b) . "0") ) : ""; } sub addbin1 { my($a,$b) = @_; $a || $b ? ( chop($a) ? (chop($b) ? addbin1($a, $b) . "1" : addbin1($a, $b) . "0") : (chop($b) ? addbin1($a, $b) . "0" : addbin0($a, $b) . "1") ) : "1"; } sub addbin { addbin0(@_) || "0"; } # multiplication algorithm to convert decimal number to binary our @dec2bin1 = qw(0 1 10 11 100 101 110 111 1000 1001); sub dec2bin { $_[0]=~/^\s*(-?)(\d+)/ or do { warn "dec2bin can not interpret its first argument as +decimal"; return "0"; }; my($sgn, $dec) = ($1, $2); $dec=~/(\d)/g or die "internal error"; # this regexp always ma +tches my $b = $dec2bin1[$1]; while($dec=~/(\d)/g) { $b = addbin($b . "0", $b . "000"); # multiply by 1010b $b = addbin($b, $dec2bin1[$1]); } $sgn . $b; } # convert a number print dec2bin($ARGV[0]), "\n"; __END__

Update: changed sub dec2bin above by merlyn's suggestion. Well, it still doesn't check for nonnumeric junk at the end of string, sorry.

Original sub:

# multiplication algorithm to convert decimal number to binary our @dec2bin1 = qw(0 1 10 11 100 101 110 111 1000 1001); sub dec2bin { $_[0]=~/^(-?)(\d*)/; my($sgn, $dec) = ($1, $2); $dec=~/(\d)/g; my $b = $dec2bin1[$1]; while($dec=~/(\d)/g) { $b = addbin($b . "0", $b . "000"); # multiply by 1010b $b = addbin($b, $dec2bin1[$1]); } $sgn . $b; }

In reply to Re: decimal to binary conversion need help by ambrus
in thread decimal to binary conversion need help by Anonymous Monk

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.