in reply to Re: decimal to binary conversion
in thread decimal to binary conversion

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

Replies are listed 'Best First'.
Re^3: decimal to binary conversion
by BrowserUk (Patriarch) on May 31, 2015 at 08:43 UTC
    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
Re^3: decimal to binary conversion
by hippo (Archbishop) on May 31, 2015 at 12:47 UTC
    What is it about the value '255' that allows the program to work correctly?

    Even a stopped clock is right twice a day.

Re^3: decimal to binary conversion
by soonix (Chancellor) on May 31, 2015 at 06:53 UTC
    Odd, isn't it? .-)