Good for using strictures (strict and warnings), but not so good for resorting to a large number of variables to store the bits. An array is a much better way to store a bunch of related data:

#!/usr/bin/perl use warnings; use strict; print "Enter a number between 0 to 256 : "; my $dec = <STDIN>; my @bits; $bits[7] = ($dec & 128) <=> 0; $bits[6] = ($dec & 64) <=> 0; $bits[5] = ($dec & 32) <=> 0; $bits[4] = ($dec & 16) <=> 0; $bits[3] = ($dec & 8) <=> 0; $bits[2] = ($dec & 4) <=> 0; $bits[1] = ($dec & 2) <=> 0; $bits[0] = ($dec & 1) <=> 0; printf "The entered decimal number in binary is : %s\n", join '', reve +rse @bits;

That makes it easier to manipulate the bits as a group which is quite an advantage when we come to printing it. However there are still too many lines of repeated code. We can fix that by calculating the bit mask from the bit index:

... my @bits; $bits[$_] = ($dec & 2 ** $_) <=> 0 for 0 .. 7; printf "The entered decimal number in binary is : %s\n", join '', reve +rse @bits;

But none of that addresses your question about (I presume) handling numbers greater than 256. However, now we have an array we can use whatever number of bits we need so:

... my @bits; while ($dec || ! @bits) { push @bits, $dec & 1; $dec >>= 1; } printf "The entered decimal number in binary is : %s\n", join '', reve +rse @bits;
True laziness is hard work

In reply to Re: decimal to binary by GrandFather
in thread decimal to binary by divyaimca

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.