Beefy Boxes and Bandwidth Generously Provided by pair Networks
laziness, impatience, and hubris

binary converter

by perlnoobz (Initiate)
on Apr 22, 2013 at 15:11 UTC ( #1029904=perlquestion: print w/replies, xml ) Need Help??
perlnoobz has asked for the wisdom of the Perl Monks concerning the following question:

i do not understand the foreach loop..can anyone explain to me what is it doing?

#!/usr/bin/perl -w print "Your binary input please =>"; $bin = <STDIN>; #read in user input chomp $bin; # use of array to store $bin and split it @digits = reverse(split('',$bin)); #reverse and split $bin, then assig +n to an array $result = 0; foreach $pos (0..$#digits) { $result += $digits[$pos] * 2 ** $pos; } print $result;

Replies are listed 'Best First'.
Re: binary converter
by Limbic~Region (Chancellor) on Apr 22, 2013 at 15:30 UTC
    I will re-write your code and explain it. I hope it makes sense and isn't more confusing to you.
    #!/usr/bin/perl use strict; use warnings; # Obtain a binary string from the user or die trying print "Your binary input please => "; chomp(my $bin = <STDIN>); die "'$bin' is not binary\n" if $bin =~ /[^01]/; # Binary numbers are easier to convert right to left # We will reverse the numbers to do this my @position = reverse split //, $bin; # Now the right most value is in the first slot of the array # And the left most value is in the last slot of the array my $tot = 0; # Normally when we loop over an array, we loop over its values # In this case, looping over its indices allows us to do powers of 2 # $#position is the last index in the array for my $idx (0 .. $#position) { $tot += $position[$idx] * 2 ** $idx; # had a typo here with $digi +t[$idx] } print "\n$tot\n";

    Cheers - L~R

      The position shoul be digit :-)

      In either case you do not need the index nor the ** operator.

      my @digit = reverse split //, $bin; my $num = 0; for my $bit (@digit) { $num = $num * 2 + $bit; } print "\n$num\n";

      Enoch was right!
      Enjoy the last years of Rome.

        Or digit should have been position.

        I wouldn't have written the code I did for myself - it was intended to be more instructional since the OP indicated not understanding the for loop. I guess I should have paid closer attention (updated now). Thanks!

        Cheers - L~R

Re: binary converter
by toolic (Bishop) on Apr 22, 2013 at 15:36 UTC
Re: binary converter
by CountOrlok (Friar) on Apr 22, 2013 at 15:18 UTC
    Try the code with a simple binary number, e.g. 100
    @digits will be (0,0,1). And $result will be 0*2^0 + 0*2^1 + 1*2^2 = 4.

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://1029904]
Approved by Corion
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others wandering the Monastery: (10)
As of 2016-12-08 21:58 GMT
Find Nodes?
    Voting Booth?
    On a regular basis, I'm most likely to spy upon:

    Results (148 votes). Check out past polls.