سؤال

In Perl, is there a bitwise operator that acts like >>, but removes the most significant bit? Sort of like how the >> operator is somewhat like the shift() function, I'm looking for a bit operator that's like pop().

110110 would return 10110

101 would return 01

Ultimately I'm trying to see whether a number in binary form is palindromic (i.e. 11011, 111, or 1010101), so ideally the operator would have a way of returning the bit it removes. It's okay if the operator doesn't, as I could do so mathematically, but in the interest of clean code, it would be awesome if it returned the MSB automatically. For the LSB, I do

$LSB=$mynum-2*($mynum>>1);
$mynum>>=1;
هل كانت مفيدة؟

المحلول

I can't think of a simpler way than just storing it as a string:

my $bits = sprintf '%b', $num;
while ( $bits =~ s/(.)// ) {
    print "removed $1\n";
}

though then your palindrome check is just

$bits eq reverse $bits

نصائح أخرى

Since your values have variable numbers of bits you need a bit string or bit vector. Check out Bit::Vector on CPAN -- it seems to still be active.

But as the others have suggested for your problem it's probably easier for you just to deal with a plain old string.

I don't know about Perl, but in C/C++ you'd do this like so:

unsigned flp2(unsigned x) {
   x = x | (x >> 1);
   x = x | (x >> 2);
   x = x | (x >> 4);
   x = x | (x >> 8);
   x = x | (x >>16);
   return x - (x >> 1);
}

unsigned most_significant_bit = flp2(my_number);
my_number &= most_significant_bit;

Courtesy of Hacker's Delight.

Note that to find the most significant bit in assembler you could use BSR, in MSVC _BitScanReverse, in GCC _builtin_clz. There are however no simple high-level (and portable) operators that I know of. Languages evolve much slower than CPUs and compilers.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top