Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterate through bits in C

Tags:

c

bit

bitarray

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.

like image 992
user16655 Avatar asked Oct 16 '14 18:10

user16655


People also ask

How to deal with bits in c?

Bitwise Operators:Bitwise operator works on bits and perform bit by bit operation. Binary AND Operator copies a bit to the result if it exists in both operands. Binary OR Operator copies a bit if it exists in eather operand. Binary XOR Operator copies the bit if it is set in one operand but not both.

What is bit in c language?

In programming terminology, a bit field is a data structure that allows the programmer to allocate memory to structures and unions in bits in order to utilize computer memory in an efficient manner. Since structures and unions are user-defined data types in C, the user has an idea of how much memory will they occupy.


2 Answers

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.

like image 191
Vinicius Kamakura Avatar answered Sep 30 '22 10:09

Vinicius Kamakura


It's true for little-endian memory architecture:

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...
  }
}
like image 21
aralex Avatar answered Sep 30 '22 10:09

aralex