I am new to perl and I need some help with the bit manipulation in perl. This is what I want to do. I have a string $str = "453D" and It needs to be masked so that only lower 8 bits are set. Then for 3D I need to find all bits set. so
$i=0;
@bitsset;
$str = $str&0xFF;
for $i(0..7)
{
$str = ($str>>1);
if($str&1)
{
push(@bitset,$i);
}
}
I wrote 开发者_开发百科this program like a C program. Can some one correct the syntax and logical errors please.
my $str = "453D";
$str = hex($str) & 0xFF;
my @bitsset;
foreach my $i (0..7) {
if ($str & 0x01) {
push(@bitset,$i);
}
$str = $str >> 1;
}
print @bitset, "\n";
Your string looks like a hexadecimal string representation of a 16-bit integer. Perl can coerce decimal string representations automatically, but needs guidance for hex.
Use one of the following:
my $str = 0x453D; # for a constant
my $str = hex '453D'; # for a variable
As for logic errors, it seems like you're shifting out the little bit out before you even read it. You might want to swap both operations.
精彩评论