Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister
 
PerlMonks  

Re: decimal to binary

by GrandFather (Saint)
on Jan 09, 2012 at 06:57 UTC ( [id://946952]=note: print w/replies, xml ) Need Help??


in reply to decimal to binary

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

Replies are listed 'Best First'.
Re^2: decimal to binary
by divyaimca (Initiate) on Jan 09, 2012 at 09:14 UTC

    Thank you grandfather for the tips. You have used some keywords unknown to me but are self explainable. But I didn't understand the logic for converting decimals greater than 256. I just started the Perl for beginners ..

      The key is $dec >>= 1; which shifts $dec one bit right - that is, it moves all the bits one position down and the previous least significant bit "drops off the end". A 0 bit is shifted in as the most significant bit so eventually all the one bits have been shifted out and the while loop ends.

      The || !@bits makes sure that there is at least one bit in @bits by executing the loop once when $dec is 0.

      I'd guess join and maybe push are new to you. I've provided links to documentation for them.

      True laziness is hard work

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://946952]
help
Chatterbox?
and the web crawler heard nothing...

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

    No recent polls found