Searching through binary (or hex) data

I have an 8 bit data and I need to find the index where the zero bit occurs. For instance, the data might be (1101 1111), so I want the program to fetch the location of the zero (third index from the MSB). The idea is similar to how a matrix keypad works, I have uploaded a picture of a smaller scale of what I meant exactly.
http://img266.imageshack.us/img266/4326/keypadqa7.jpg

B7-B4 are considered outputs where the 0 bit is going to be written to them one a time. Searching for a zero bit through B3-B0 (inputs) would help us identify the node number. For example if B7=0, and reading B3-B0 we found B3 is 0, then the program should return node 1.

Any help to search through a binary data bit by bit, find the zero and match it with node number.

I know there is a bsearch class, but I'm not sure how to use or whether it is going to be helpful in what I'm asking for.

Thanks in advance
It's a matter of using the >> (bitshift) operator and the & (bitwise-and) operator like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <stdio.h>
typedef unsigned char Byte;

/*  The bits are numbered like this:
      7 6 5 4 3 2 1 0
    If no zero bit is found, returns -1.
 */

int find_zero_bit( Byte b )
{
    int i;
    for( i = 0; i < 8 && b & 1; ++i )
        b >>= 1;
    return (i < 8) ? i : -1;
}

int main()
{
    Byte b = 0xDF;
    int index = find_zero_bit( b );
    printf( "%d\n", index );
}
Last edited on
amazing, worked like a charm.
I guess this loop stops once a zero bit index is found and returns it.
What about if I want to identify the index for more than one zero bit. So lets say we have : 10010111, I want the program to return and array that has the values 6,5,3. How about can I do that?

Thanks
Last edited on
Solved
Topic archived. No new replies allowed.