Iterate through bits in C

I have a big char * str, where the first 8 characters (which is 64 bits, if I'm not mistaken) represents a bitmap. Is there any way to iterate over these 8 characters and see which bits are 0? I have many problems understanding the concept of bits, since you cannot “see” them in the code, so I cannot think of any way to do this.

+4
source share
5 answers

Imagine you only have one byte, one char my_char. You can check for individual bits using bitwise operators and bit offsets.

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;
}

, , >>. " , - ".

1.

+7

little-endian:

const int cBitmapSize = 8;
const int cBitsCount = cBitmapSize * 8;
const unsigned char cBitmap[cBitmapSize] = /* some data */;

for(int n = 0; n < cBitsCount; n++)
{
  unsigned char Mask = 1 << (n % 8);
  if(cBitmap[n / 8] & Mask)
  {
    // if n'th bit is 1...
  }
}
+2

C 8- , , , .

, , , , . SO- C.

, - AND , :

int isBitSet = bitmap & (1 << bit_position);

isBitSet 0, . , .

+1

char b :

for (int i=0; i<8; i++) {
  printf("This is the %d-th bit : %d\n",i,(b>>i)&1);
}

.

, , , 2 , - , .

, ? char 8 . A char , 8 2. b b7b6b5b4b3b2b1b0 ( ), b → b, ( 0 ). , 10110111 → 2 00101101, 1 ( ).

+1

( , , ), .

:

#define LSBIT(X)                    ((X) & (-(X)))
#define CLEARLSBIT(X)               ((X) & ((X) - 1))

, LSbit:

unsigned temp_bits;
unsigned one_bit;

temp_bits = some_value;
for ( ; temp_bits; temp_bits = CLEARLSBIT(temp_bits) ) {
    one_bit = LSBIT(temp_bits);
    /* Do something with one_bit */
}

, . , 0, 1 bits - , . for .

+1

All Articles