http://www.perlmonks.org?node_id=715099


in reply to Bitwise Operator Error

You could also avoid going numeric altogether by converting your string to a bitstring (a string of ASCII 0's and 1's, that is, here):

my $testString = " 00008008 000000FF 00800000"; $testString =~ s/\s+//g; # convert to a string representation of '0's and '1's my $bits = unpack("B*", pack("H*", $testString)); # test if specific bit is set my $maskResult = substr($bits, 1, 1) eq '1'; printf "%s\n--> 2nd bit from left: %d\n", $bits, $maskResult;

Checking for several non-adjacent bits with substr might get a bit unwieldy (if you need that) ... in which case you could use the bitwise string-AND operation. For example

my $testString = " 01008008 000000DF 00800000"; my $mask = "42000000 00000020 00000000"; for ($testString, $mask) { s/\s+//g; $_ = pack("H*", $_); # convert from hex to (binary) bitstring } # bitwise string AND my $maskResult = $testString & $mask; # ----- visualise what's going on (functionally not required) ----- for my $bits ($testString, $mask, '', $maskResult) { if ($bits) { print unpack("B*", $bits), "\n"; } else { print "-" x 96, "\n"; } } # --------------------------------------------------------------- # check for any non-zero bytes $maskResult =~ tr/\0//d; printf "There were %s matching bits.\n", length($maskResult) ? "some": +"no";

This would test whether any of the bits specified in $mask are set in $testString.

There is always more than one way to do it :)