Beefy Boxes and Bandwidth Generously Provided by pair Networks
Syntactic Confectionery Delight

Re: Bitwise Operator Error

by almut (Canon)
on Oct 02, 2008 at 21:46 UTC ( #715099=note: print w/replies, xml ) Need Help??

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 :)

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://715099]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others studying the Monastery: (4)
As of 2018-02-25 16:43 GMT
Find Nodes?
    Voting Booth?
    When it is dark outside I am happiest to see ...

    Results (314 votes). Check out past polls.