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
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.