Hi Monks, I've been having a really hard time getting this code to work right and I'm betting you'll see instantly what I've done wrong. I'm passing an integer representation to a script, packing it as a binary string and then and'ing against a binary switch stored in a hash. However when it gets to the portion that does the &'ing for some reason it appears to be treating the binary packed string as an integer value and is decoding wrong

my %SWITCH = ( CAT => 0b00001, DOG => 0b00010, HAMSTER => 0b00100, FERRIT => 0b01000, FISH => 0b10000); my $petInput = 2; my @PETS; my $binPet = unpack("B32", pack("N", $petInput)); $binPet =~ s/^0+(?=\d)//; # gets rid of leading zeros printf "%s%bn%s", "\n", $binPet, "\n"; # at this point $binPet unfortunately contains "0b1010" # rather than 0b10 as expected, so I'm doing something wrong # in my pack/unpack apparently for (keys %SWITCH) { if ($binPet & $SWITCH{$_}){push (@PETS, $_);} } foreach (@PETS){print $_."\n";}

This results in DOG, FERRIT when it should just be DOG. What am I missing here? Thank You Monks!!!!


In reply to having trouble unmasking a binary string by emoss1

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.