bit - How to do bitwise operation in perl to get the count of longest sequence of 0s between two 1s -
given integer print bit bit in perl. instance given number 9, get
1 0 0 1
how achive this. trying is, number of longest 0s between 2 1s. meaning if bitwise representation of number 1000001001, perl function return 5.
i know whats best way code in perl. totally new perl.
with leading zeroes:
my @bits = reverse unpack '(a)*', unpack 'b*', pack 'j>', $int;
without:
my @bits = reverse unpack '(a)*', sprintf '%b', $int;
notes:
reverse
used place least significant bit in$bits[0]
.unpack '(a)*'
used split string individual bits.- both work signed , unsigned integers.
- both work integers of size (in bytes) given
perl -v:ivsize
.
if leave string, can take advantage of regex engine extract sequences of zeroes.
use list::util qw( max ); $bin = sprintf '%b', $num; $longest = ( max map length, $bin =~ /1(0+)(?=1)/g ) || 0;
in c, might following, in perl, might less efficient earlier solution:
my $longest = 0; if ($num) { # cast unsigned >> inserts zeroes neg nums. $num = ~~$num; # skip zeros not between 1s. $num >>= 1 while !($num & 1); while (1) { # skip 1s. $num >>= 1 while $num & 1; last if !$num; # count 0s. $len = 0; ++$len, $num >>= 1 while !($num & 1); $longest = $len if $longest < $len; } }
Comments
Post a Comment