Thread: Check Bits

  1. #1
    Registered User
    Join Date
    Mar 2008
    Posts
    1

    Check Bits

    Can any one tell me how to search through the bits of a number an locate the position of each one or zero?

  2. #2
    Just Lurking Dave_Sinkula's Avatar
    Join Date
    Oct 2002
    Posts
    5,005
    Something like this, perhaps?
    7. It is easier to write an incorrect program than understand a correct one.
    40. There are two ways to write error-free programs; only the third one works.*

  3. #3
    Registered User
    Join Date
    Jun 2007
    Posts
    63
    To check for the proper bit in a bitmap you have to create a function that will contain a valid mask and shift the mask across the bitmap. Using bitwise operations you can easily get the value of the bit in the given positio. I will provide you some code for that to get in mind.

    Code:
    #include <stdio.h>
    
    /* Get the bit value from a given position in a bitmap. */
    
    int GetBit(char bitmap[], int BitPosition)
    {
    	short int Index = 0;
    	unsigned char mask = 0x80;
    	int Byte =(int)(BitPosition /  (8 *sizeof(char)));
    	int nrShifts = BitPosition % (8 * sizeof(char));
    	for(Index = 0; Index < nrShifts; Index++)
    		mask >>= 1;
    	return bitmap[Byte] & mask;
    }
    
    /* More usefull stuff. */
    
    int IndexOfBit(char b[], int BitSize, int startIndex, int value)
    {
    	unsigned char mask = 1 << (8 * sizeof(char) - 1 - (startIndex % 8));
    	char *p = b + (startIndex / (sizeof(char) * 8));
    	while(startIndex < BitSize)
    	{
    		if(!mask)
    		{
    			p++;
    			mask = mask = 1 << (8 * sizeof(char) - 1);
    		}
    		if (value && (mask & (unsigned char)*p) || !value && !(mask & (unsigned char)*p))
    			return startIndex; /* Found our bit. */
    		mask >>= 1;
    		startIndex++;
    	}
    	return -1;
    }

  4. #4
    Just Lurking Dave_Sinkula's Avatar
    Join Date
    Oct 2002
    Posts
    5,005
    7. It is easier to write an incorrect program than understand a correct one.
    40. There are two ways to write error-free programs; only the third one works.*

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. BN_CLICKED, change button style
    By bennyandthejets in forum Windows Programming
    Replies: 13
    Last Post: 07-05-2010, 11:42 PM
  2. merging bits
    By Drac in forum C++ Programming
    Replies: 8
    Last Post: 12-21-2008, 06:13 PM
  3. SDLKey to ASCII without unicode support?
    By zacs7 in forum Game Programming
    Replies: 6
    Last Post: 10-07-2007, 03:03 AM
  4. Replies: 7
    Last Post: 08-19-2007, 08:10 AM
  5. Help counting number of bits set in an integer
    By JayDiddums10 in forum C Programming
    Replies: 5
    Last Post: 12-07-2006, 03:21 PM