in reply to Binary File Manipulation across Byte boundaries

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.