Let's deal with the more familiar first and ask ourselves how someone could convert a number to its decimal representation. Converting a number to its decimal representation is to build a string consisting of its digits.

Well, we know that one can decompose a number into its digits as follows,

846 = 8*(10**2) + 4*(10**1) + 6*(10**0)

So a particular digit can be obtained as follows:

units: ( int($num / (10**0)) ) % 10 tens: ( int($num / (10**1)) ) % 10 hundreds: ( int($num / (10**2)) ) % 10

Bits are to number in binary as digits are to numbers in decimal, so converting a number to its binary representation is to build a string consisting of all its bits. The same approach can be taken.

23 = 1*(2**4) + 0*(2**3) + 1*(2**2) + 1*(2**1) + 1*(2**0)
bit 0: ( int($num / (2**0)) ) % 2 bit 1: ( int($num / (2**1)) ) % 2 bit 2: ( int($num / (2**2)) ) % 2 ... bit 7: ( int($num / (2**3)) ) % 2

The thing is, there are more efficient tools for dealing with binary.

int($i / (2**$j))

can be written as

$i >> $j

and

$k % 2

can be written as

$k & 1

We end up with

bit 0: ( $num >> 0 ) & 1 bit 1: ( $num >> 1 ) & 1 bit 2: ( $num >> 2 ) & 1 ... bit 7: ( $num >> 7 ) & 1

Now just put that in a loop, and you're done.

That said, I would just use sprintf "%08b", $num.


Based on the hint, I think they're expecting you to use the following, but this is Perl not C.

bit 0: ( $num & (1 << 0) ) >> 0 = ( $num & (1 << 0) ) ? '1' : '0' bit 1: ( $num & (1 << 1) ) >> 1 = ( $num & (1 << 1) ) ? '1' : '0' bit 2: ( $num & (1 << 2) ) >> 2 = ( $num & (1 << 2) ) ? '1' : '0' ... bit 7: ( $num & (1 << 7) ) >> 7 = ( $num & (1 << 7) ) ? '1' : '0'

In reply to Re: binary conversion by ikegami
in thread binary conversion by saintj0n

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.