Beefy Boxes and Bandwidth Generously Provided by pair Networks
P is for Practical
 
PerlMonks  

comment on

( [id://3333]=superdoc: print w/replies, xml ) Need Help??

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":



  • 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.
Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others examining the Monastery: (8)
As of 2024-04-25 11:34 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found