Your example looks essentially trivial, so I wonder if there's a larger problem that you are trying to solve ?

The obvious bit-twiddling way to do this is:

my $b = 7 ; # Number of bits to worry about my $p = ($b + 1) >> 1 ; # Number of pairs of bits to consider my $cnt = 0 ; for my $v (0..((2**$b)-1)) { my $m = 0b11 ; for (1..$p) { if ($v & $m) { $m <<= 2 ; } else { $cnt++ ; last ; } ; } ; } ;
this will work for $v up to the largest unsigned integer supported on your machine -- though it gets tedious waiting.

With $b = 7 you could save time by starting at $v == 85 and $cnt = 84, or more generally:

... my $iv = 0 ; for (1..$p) { $iv = ($iv << 2) + 1 ; } ; my $cnt = $iv ; for my $v ($iv..((2**$b)-1)) { ...

If you want to do this for longer bit-strings than will fit in an unsigned integer, then vec could be your friend... but you may have difficulty counting (also be prepared for a long wait).

If bit-twiddling looks too much like 'C', then:

my $f = "%0".($b + ($b & 1))."b" ; my $cnt = 0 ; $cnt += sprintf($f, $_) =~ m/^(?:01|10|11)*00/ for 0..((2**$b)-1) ;
will do the job. Usually with Perl, the avoiding of explicit loops make things faster. In this case, not (on my machine, anyway).

For limited values of $b you can do things two pairs of bits at a time:

my $f = "%0".(($b + ($b & 1)) >> 2)."X" ; my $cnt = 0 ; $cnt += sprintf($f, $_) =~ m/[012348C]/ for 0..((2**$b)-1) ;

Of course, this is all unnecessarily complicated. For $b bits you have 3**($b >> 1) values where none of the bit pairs are zero. I wonder what the real problem is...


In reply to Re: binary string by gone2015
in thread binary string by alih110

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.