Bit map algorithms needed

simon ewins simon.ewins at f664.n250.z1.fidonet.org
Fri Jun 1 10:13:00 AEST 1990


> From: jharkins at sagpd1.UUCP (Jim Harkins)
> Orga: Scientific Atlanta-GPD, San Diego
> 
> I need to implement what I think of as a sliding window over a long
> string of bits. I have a bitmap spread across several words and I
> need to find a set of N adjacent bits that are set,
 
 
I have had good success with this... You can adjust as needed but the
idea should work as it has for me.  The following code can handle bit-
arrays of any length.
 
 
#include <stdio.h>
 
#define SET 1
#define CLR 2
#define GET 3
 
 
main()
{
   unsigned char bit_array[8];
   int i;
 
   /*
   ** clear the array to 0's
   */
   for(i=0;i<8;i++) bit_array[i]=NULL;
 
   /*
   ** show bit 23 on/off           Off
   ** set bit 23 on
   ** show bit 23 on/off           On
   ** show bit 22 on/off           Off
   ** show bit 24 on/off           Off
   ** set bit 24 on
   ** show bit 24 on/off           On
   ** set bit 24 off
   ** show bit 24 on/off           Off
   **
   ** etc. etc. etc...
   */
 
   printf("Bit 23: %s\n",bit(GET,23,bit_array) ? "On" : "Off");
   bit(SET,23,bit_array);
   printf("Bit 23: %s\n",bit(GET,23,bit_array) ? "On" : "Off");
   printf("Bit 22: %s\n",bit(GET,22,bit_array) ? "On" : "Off");
   printf("Bit 24: %s\n",bit(GET,24,bit_array) ? "On" : "Off");
   bit(SET,24,bit_array);
   printf("Bit 24: %s\n",bit(GET,24,bit_array) ? "On" : "Off");
   bit(CLR,24,bit_array);
   printf("Bit 24: %s\n",bit(GET,24,bit_array) ? "On" : "Off");
}
 
 
/*
** set, get or clear bit in a character array ... This is NOT range checked
** ... garbage in, garbage out ... so make sure that the bit number is in
** the range of the size of the character array * 8 AND that the action is
** only one of GET, SET, or CLR
*/
bit(action,bit_pos,array)
unsigned char array[];
int action;
int bit_pos;
{
   unsigned char test_val;
   int index;
 
   index=bit_pos/8;      /* element of array to test */
   switch(bit_pos%8) {   /* bit in indexth element to get, set, or clear */
   case 0: test_val=0x01; break;
   case 1: test_val=0x02; break;
   case 2: test_val=0x04; break;
   case 3: test_val=0x08; break;
   case 4: test_val=0x10; break;
   case 5: test_val=0x20; break;
   case 6: test_val=0x40; break;
   case 7: test_val=0x80; break;
   }   
   switch(action) {
   case GET:
      if((array[index]&test_val)==test_val)
         return(TRUE);
      return(FALSE);
   case SET:
      array[index]|=test_val;
      return(TRUE);
   case CLR:
      array[index]&=(0xff-test_val);
      return(FALSE);
   }
}
 
 
/* end */

--- D'Bridge 1.30/002506
 * Origin: A_X_A_X_A  [ FactBase/qDos <> 416-483-2821 ] (1:250/664)



More information about the Comp.lang.c mailing list