Beefy Boxes and Bandwidth Generously Provided by pair Networks
XP is just a number

How do I convert between decimal and binary?

by vroom (Pope)
on Feb 01, 2000 at 23:46 UTC ( #2664=categorized question: print w/replies, xml ) Need Help??
Contributed by vroom on Feb 01, 2000 at 23:46 UTC
Q&A  > numbers

Answer: How do I convert between decimal and binary?
contributed by vroom

We need to use pack and unpack because printf or sprintf don't have any way of dealing with binary numbers. Here are two functions that should do the job though:

sub dec2bin { my $str = unpack("B32", pack("N", shift)); $str =~ s/^0+(?=\d)//; # otherwise you'll get leading zeros return $str; } sub bin2dec { return unpack("N", pack("B32", substr("0" x 32 . shift, -32))); }
To turn a perl integer into a binary string we must first pack it into network byte order which the "N" format stands for. Then we unpack it into the "B32" format. We then strip off all leading 0's with a simple substitution.

For the bin2dec function we simply reverse the process. First we pad the number with the correct number of 0's and then reversing what we did in the previous function
Answer: How do I convert between decimal and binary?
contributed by I0

In v5.6.0 there's $bin = sprintf "%b",$dec; and $dec = oct "0b$bin";

Please (register and) log in if you wish to add an answer

  • 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, 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, 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.
  • Log In?

    What's my password?
    Create A New User
    and the web crawler heard nothing...

    How do I use this? | Other CB clients
    Other Users?
    Others romping around the Monastery: (3)
    As of 2018-08-22 05:39 GMT
    Find Nodes?
      Voting Booth?
      Asked to put a square peg in a round hole, I would:

      Results (204 votes). Check out past polls.