1

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;
Zero Piraeus
  • 56,143
  • 27
  • 150
  • 160
Jake Stevens-Haas
  • 1,186
  • 2
  • 14
  • 26

4 Answers4

2

see How to check if the binary representation of an integer is a palindrome?

Community
  • 1
  • 1
  • You know, I spent way too long looking for something just like that to not have found it. What does WORDSIZE mean in that example? – Jake Stevens-Haas Dec 22 '10 at 05:44
  • @Ranting_Raven, I posted it in case you missed it. WORDSIZE is the size of a word on your machine (I assume) –  Dec 22 '10 at 21:21
2

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
ysth
  • 96,171
  • 6
  • 121
  • 214
1

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.

hippietrail
  • 15,848
  • 18
  • 99
  • 158
0

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.

martona
  • 5,760
  • 1
  • 17
  • 20