A straightforward, if slow, implementation could create an interface to read a single bit of the file at a time, and use a circular buffer to compare the last n bits to the pattern you're looking for. For example, this code:
#!/usr/bin/perl -w use strict; use constant BLOCKSIZE => 1024; # Bytes # Create the getbit function in a closure. # This only supports one filehandle at a time { my @bits; sub getbit(*) { my($fh)=@_; if (!@bits) { my $block; read($fh,$block,BLOCKSIZE) or return undef; @bits=split('',unpack('B*',$block)); } return shift @bits; } } # Compare two lists sub listcmp(\@\@) { my($l1,$l2)=@_; @$l1 == @$l2 or return undef; foreach my $i (0..$#$l1) { $l1->[$i] == $l2->[$i] or return undef; } return 1; } use constant PRINTBITS => 4; my @PATTERN=(1,1,1,1); my @lastbits; my $interval; while (defined(my $bit = getbit(STDIN))) { push(@lastbits,$bit); shift @lastbits if (@lastbits > @PATTERN); if (listcmp(@lastbits,@PATTERN)) { print "Found sequence"; print "(last seen $interval bits ago)." if (defined($interval)); print "\n"; my @bits = map { getbit(STDIN) } (1..PRINTBITS); while (my @b4 = splice(@bits,0,4)) { printf "%x ",ord(pack('B*',join('',0,0,0,0,@b4))); } print "\n"; $interval=-1; @lastbits=(); } $interval++ if (defined($interval)); }
looks for a pattern of 4 consecutive ones, and prints out the next nybble.

In reply to Re: Binary File Manipulation across Byte boundaries by sgifford
in thread Binary File Manipulation across Byte boundaries by tperdue

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.