in reply to decimal to binary conversion

You have a precedence problem. Modify your print lines to be: print +( $decimal & nnn ) <=> 0;


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.
"Science is about questioning the status quo. Questioning authority". I'm with torvalds on this
In the absence of evidence, opinion is indistinguishable from prejudice. Agile (and TDD) debunked

Replies are listed 'Best First'.
Re^2: decimal to binary conversion
by NetWallah (Canon) on May 31, 2015 at 01:06 UTC
    What is it about the value '255' that allows the program to work correctly ?
    $ perl -E 'say 254 & 2 <=> 0' 0 $ perl -E 'say 255 & 2 <=> 0' 1

            "Despite my privileged upbringing, I'm actually quite well-balanced. I have a chip on both shoulders."         - John Nash

      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.
      "Science is about questioning the status quo. Questioning authority". I'm with torvalds on this
      In the absence of evidence, opinion is indistinguishable from prejudice. Agile (and TDD) debunked
      What is it about the value '255' that allows the program to work correctly?

      Even a stopped clock is right twice a day.

      Odd, isn't it? .-)