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

Hi, is there a function in perl that translate decimal number to binary number? Thanks, Tsvika.

Replies are listed 'Best First'.
Re: decimal to binary
by jeroenes (Priest) on Jan 23, 2001 at 21:00 UTC
    Do something like:
    print unpack('b32',pack('L',$num));
    See pack/unpack for more details. You need other types for floats ('b128','d') or other integer types.

    Hope this helps,

    Jeroen
    "We are not alone"(FZ)

    Update: Noticed the posts of tadman and stefan_k. From stefan_k's link I understand that binary sprintf is only available in perl 5.6 or higher.

Re: decimal to binary
by Gloom (Monk) on Jan 23, 2001 at 21:44 UTC
    Maybe you don't understand why I don't use pack/unpack... Only for illustrate the well known TIMTOWTDI :)
    sub to_bin { my $num = shift; my $size = 0; my @result; while( $num >> $size ) { $size ++;} for (0..$size-1) { unshift @result , ( ($num & ( 2 ** $_ ) ) ? "1" : "0" ); } return join '' , @result ; }
      I'm working on it and I have found shortest way to do that
      sub to_bin { my( $num , $len ) = ( shift , 0 ); while( $num >> $len ){ $len++ ;} return reverse map {( $num & 1 << $_ ) ? "1" : "0";}(0..$len-1); }
      did someone can do better ? ( I'm sure you can, I trust in you ;)
        Another WTDI.

        A one liner (I'm no true obfuscator):
        perl -ne 'undef@_;while($_){$_[0]=($_&1&&1||0).$_[0];$_>>=1}print"@_\n"'

        Or a more sensible sub version with the same logic.

        sub to_bin { my $num = shift; my $ret = ''; while ($num) { $ret = (($num % 2) ? 0 : 1) . $ret; $num >>= 1; } return $ret; }
Re: decimal to binary
by tadman (Prior) on Jan 23, 2001 at 21:01 UTC
    You could always use sprintf():
    my ($binary) = sprintf ("%08b", $decimal);
Re: decimal to binary
by stefan k (Curate) on Jan 23, 2001 at 21:04 UTC
    A very simple search for "decimal" on the perlmonks would (among others) present you this:
    How do I convert between decimal and binary?

    You could have found that easily ...

    regards
    Stefan K
    $dom = "skamphausen.de"; ## May The Open Source Be With You! $Mail = "mail@$dom; $Url = "http://www.$dom";
Re: decimal to binary
by InfiniteSilence (Curate) on Jan 23, 2001 at 21:05 UTC
    This exact same question was asked last year in May.

    The search engine is your friend. Use it and post if you find nothing.

    Celebrate Intellectual Diversity