I can't see any major problem — only a minor one, which is that [$bitmask] should most likely have been [$bitmask_value] :)

In other words, & is the correct operator to test if certain bits are set.

In case you want to test if more than one bit is set, you should check if the masked value equals the mask, not only if it's true, i.e.

if (($value & $mask) == $mask) ...

Example:

my $mask = 0b00001110; # test if bits 2,3,4 are set check($_, $mask) for 0b01101110, 0b01100110; sub check { my ($value, $mask) = @_; printf " val %08b\n", $value; printf "mask %08b\n", $mask; print " & --------\n"; printf " %08b ", $value & $mask; if ( ($value & $mask) == $mask ) { # equals mask? print "=> all tested bits set"; } elsif ( $value & $mask ) { # just true? print "=> some tested bits set"; } print "\n\n"; } __END__ val 01101110 mask 00001110 & -------- 00001110 => all tested bits set val 01100110 mask 00001110 & -------- 00000110 => some tested bits set

In reply to Re: bitmask check by Eliya
in thread bitmask check by wwe

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.