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 :)
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
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, 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, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
Outside of code tags, you may need to use entities for some characters:
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.
|
|