I'm not going to give you the program, but I'll give you some hints that may help you figure out the answer.

In the binary representation of a number, a value is made up of a certain number of bits. For values less than 256, as in your question, this requires 8 bits (also known as 1 byte).

Binary numbers are just like our usual decimal numbers - all that changes is the number base. 2 for binary, 10 for decimal.

So, in decimal, 250 is 2*100 + 5*10 + 0*1, while the same number in binary is 11111010 (1 * 128 + 1*64 + 1*32 + 1*16 + 1*8 + 0*4 + 1*2 + 0*1).

The bitwise and operator & works on the bits that make up a number. So 250&32 is going to return 32, because that bit is on in 250, but 250&1 is going to return 0, because the 1's bit is not on in 250.

So, by using & with masks 1, 2, 4, 8, 16, 32, 64, and 128, you should be able to build up the binary representation of your input number...

As a bonus feature, perl's printf implementation allows the "%b" specifier to be used, so you can use that to quickly implement tests for your & implementation.


Mike

In reply to Re: Decimal to Binary using Bitwise and operator by RMGir
in thread Decimal to Binary using Bitwise and operator by AchyuthaRao

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.