Search code examples
perlbit-manipulationbitvector

Bit operation equivalent of pop function in PERL(remove MSB)


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;

Solution

  • 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