cbitbitarray

Iterate through bits in C


I have a big char *str where the first 8 chars (which equals 64 bits if I'm not wrong), represents a bitmap. Is there any way to iterate through these 8 chars and see which bits are 0? I'm having alot of trouble understanding the concept of bits, as you can't "see" them in the code, so I can't think of any way to do this.


Solution

  • Imagine you have only one byte, a single char my_char. You can test for individual bits using bitwise operators and bit shifts.

    unsigned char my_char = 0xAA;
    int what_bit_i_am_testing = 0;
    
    while (what_bit_i_am_testing < 8) {
      if (my_char & 0x01) {
         printf("bit %d is 1\n", what_bit_i_am_testing);
      }
      else {
         printf("bit %d is 0\n", what_bit_i_am_testing);
      }
    
      what_bit_i_am_testing++;
      my_char = my_char >> 1;
    }
    

    The part that must be new to you, is the >> operator. This operator will "insert a zero on the left and push every bit to the right, and the rightmost will be thrown away".

    That was not a very technical description for a right bit shift of 1.