Alex_adl04
Alex_adl04

Reputation: 560

Bitwise Operator & Logic

I need clarification on a problem that I have. I am currently trying to learn Perl using the Beginning Perl book provided by the "Learn Perl" portion of the Perl website. I am down to the ending of chapter 2 and I am currently having a hard time trying to understand the logic behind a solution that the book provided.

#!usr/bin/perl
#Ex2_3.plx
use warnings;


print "Please enter the value(less than 256) you wish to be converted into binary\n";
my $bin = <STDIN>;
chomp ($bin);

print "The binary value of $bin is : ", "\n";

#Use the bitwise and operator to determine the binary value:


print((128 & $bin) / 128);
print((64 & $bin) / 64);
print((32 & $bin) / 32);
print((16 & $bin) / 16);
print((8 & $bin) / 8);
print((4 & $bin) / 4);
print((2 & $bin) / 2);
print((1 & $bin) / 1);
print("\n");

I can't seem to understand the logic behind (128 & n) / 128 and so forth. While I do understand why is it that the code needs to go from 128 down to 1 I can't seem to grasp the solution after &. I feel bad because I normally hate looking at solutions, but this is all very intriguing to me, most other programming books put very small(if any) attention to bitwise operators. I will appreciate the help.

Upvotes: 1

Views: 757

Answers (2)

NigoroJr
NigoroJr

Reputation: 1106

For example, decimal 128 is 10000000 in binary. &ing with this gives you the bit of the most significant bit. / 128 part is the same as shifting the bits to the right 7 times, since dividing the number by 2 is the same as shifting one bit to the right.

  10000000 (= 128)
& 10000110 (= 134)
  10000000

shifting 7 bits to the right, you get 1

Now, doing the same thing for 64

  01000000 (= 64)
& 10000110 (= 134)
  00000000

shifting 6 bits to the right (because 64 = 2^6), you get 0

Do this for the rest of the bits, you would get 1, 0, 0, 0, 0, 1, 1, 0, which would look 10000110 from the print statements.

The code from the book is basically the same as this:

#!/usr/bin/perl

use strict;
use warnings;

chomp(my $input = <STDIN>);

for (my $i = 7; $i >= 0; $i--) {
    print( (($input & (1 << $i)) >> $i) );
}

print "\n";

Upvotes: 2

Miller
Miller

Reputation: 35198

The numbers 1,2,4,8 are all powers of 2. So the bitwise & of any number with them will only have 2 possible values, The power of 2 or 0.

Then taking the result and dividing it by itself will give a result of either 0 or 1.

By the way, the easier method to convert a number to binary is to use sprintf:

sprintf "%b", 145;

Outputs:

10010001

Upvotes: 1

Related Questions