FindFirstBitRun C function
Wed, 24 Jun 2009 18:27:50 -0400 - Author:
This public domain function called FindFirstBitRun is written in C. It's
documented below. I hope this will help anyone.
documented below. I hope this will help anyone.
/*
* Finds the next run of bits in a bit buffer and returns its
* index and size.
*
* @param buffer Points to a buffer of bits. Can't be null; if so, returns 0
* @param numbits Number of bits in the buffer
* @param start Points to the first bit to check, when the function returns,
* this points to the index of the next bit run. This parameter can't
* be null; if so, returns 0
* @param bitorder Specifies the order of bits in each bytes. If 0, the order
* is least-significant bit first; if 1, the order is most significant
* bit first.
* @param findSet If 1, this function will find the next set run of bits,
* if 0, this function will find the next clear run of bits
* @return Number of bits in the next bit run
*/
DWORD FindFirstBitRun(
LPBYTE buffer,
DWORD numbits,
LPDWORD start,
BOOL bitorder,//if 1, MSB first
BOOL findSet//if 1, find first set run; if 0, find first clear run
){
LPBYTE sp,dp;
int sshift;
int sstart,send,sinc;
BYTE v;
DWORD index,count;
BYTE beginMask=(findSet)?0:1;
BYTE endMask=(findSet)?1:0;
if(!start)return 0;
if(!buffer || *start>numbits){
*start=(DWORD)-1;
return 0;
}
index=*start;
sp=buffer+(index>>3);
if(bitorder==1){
sshift=7-(index&7);
sstart=7;
send=0;
sinc=-1;
} else {
sshift=(index&7);
sstart=0;
send=7;
sinc=1;
}
for(;index>sshift)&0x01);
if(v^beginMask)break;
if(sshift==send){sshift=sstart;sp++;}
else sshift+=sinc;
}
if(index>=numbits){
*start=(DWORD)-1;
return 0;
} else {
*start=index;
}
for(count=0;index>sshift)&0x01);
if(v^endMask)break;
if(sshift==send){sshift=sstart;sp++;}
else sshift+=sinc;
}
return count;
}
