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

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


Comment on Re: Bitwise Operator Error
Select or Download Code

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://715099]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others making s'mores by the fire in the courtyard of the Monastery: (8)
As of 2014-08-27 23:54 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The best computer themed movie is:











    Results (253 votes), past polls