I'm assuming that this question is associated with the generation of arrays of nybbles in the Bit manipulation of a bit stream to generate different elements of an array with each nibble taking either 0 or 1 in perl post and that you might want to act on any element of the array, not just those in which all nybbles are 1111. If so, you can create a mask where nybbles to leave untouched are set to 1111 and those to zero are set to 0000 then AND it with the relevant array element. It is not clear from the OP but I'm also assuming that your offset is one-based counting from the right in bits, i.e. offsets 1 through 4 mask the rightmost nybble, 5 through 8 the rightmost two nybbles etc. The code is simple to modify if counting is zero-based.
use strict;
use warnings;
use feature qw{ say };
my $sep = sub { say q{-} x 24; };
my $baseStr = q{{0,f}};
my $width = 4;
my $globStr = $baseStr x $width;
$sep->();
foreach my $offset ( 3, 5, 8, 9 )
{
say qq{Offset - $offset};
my @bitStrs = map { pack q{H*}, $_ } glob $globStr;
my $div = int( $offset / 4 );
my $rem = $offset % 4;
my $nybblesToMask = $div + ( $rem ? 1 : 0 );
my $mask = pack q{H*},
q{f} x ( $width - $nybblesToMask ) . q{0} x $nybblesToMask;
say q{Mask - }, unpack qq{B@{ [ $width * 4 ]}}, $mask;
say q{Element 5 - }, unpack qq{B@{ [ $width * 4 ]}}, $bitStrs[
+5 ];
say q{E. 5 & mask - }, unpack qq{B@{ [ $width * 4 ]}},
$bitStrs[ 5 ] & $mask;
say q{Element 15 - }, unpack qq{B@{ [ $width * 4 ]}}, $bitStrs[
+15 ];
say q{E. 15 & mask - }, unpack qq{B@{ [ $width * 4 ]}},
$bitStrs[ 15 ] & $mask;
$sep->();
}
The output.
------------------------
Offset - 3
Mask - 1111111111110000
Element 5 - 0000111100001111
E. 5 & mask - 0000111100000000
Element 15 - 1111111111111111
E. 15 & mask - 1111111111110000
------------------------
Offset - 5
Mask - 1111111100000000
Element 5 - 0000111100001111
E. 5 & mask - 0000111100000000
Element 15 - 1111111111111111
E. 15 & mask - 1111111100000000
------------------------
Offset - 8
Mask - 1111111100000000
Element 5 - 0000111100001111
E. 5 & mask - 0000111100000000
Element 15 - 1111111111111111
E. 15 & mask - 1111111100000000
------------------------
Offset - 9
Mask - 1111000000000000
Element 5 - 0000111100001111
E. 5 & mask - 0000000000000000
Element 15 - 1111111111111111
E. 15 & mask - 1111000000000000
------------------------
I hope this is helpful.
Update: Clarified wording re the offset.
|