What is it about the value '255' that allows the program to work correctly ?
255 has all ones. Thus if the program tests the same bit and prints 1, 8 times it just looks like it worked.
It didn't. Any value that has the first bit set will also produce a 1:
say 253 & 2 <=> 0;;
Using the OPs original code, the fact that only the first bit is being tested becomes obvious when you enter a 1: C:\test>perl
#!/usr/bin/perl -w
use strict;
use warnings;
print "Enter decimal number less than 256:";
my $decimal;
$decimal=<STDIN>;
#chomp $decimal;
print $decimal & 128 <=> 0;
print $decimal & 64 <=> 0;
print $decimal & 32 <=> 0;
print $decimal & 16 <=> 0;
print $decimal & 8 <=> 0;
print $decimal & 4 <=> 0;
print $decimal & 2 <=> 0;
print $decimal & 1 <=> 0 ;
^Z
Enter decimal number less than 256:1
11111111
And the fact that 255 appeared to work, is just coincidence.
With the rise and rise of 'Social' network sites: 'Computers are making people easier to use everyday'
Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
|