Question

I have a function that takes a buffer of size 2kB and loads certain content to it. I can assume the function works properly, but i can't test it.

The function prototype is

int loadContent(unsigned long, char* buffer);

Unsigned long is the number of a block i want to load (the size is fixed to 2kB for every block), and the buffer is where the content is loaded.

Now i have to iterate bit by bit through the buffer and find the first bit that equals 1.

To make sure buffer is sized 2kB i made a variable

char buffer[2048];

But how do i iterate bit-by-bit through array of chars?

Would something like this be okay?

unsigned long getFreeCluster(){
    char helpbuffer[2048];
    partition->readCluster(0, helpbuffer);
    unsigned long comparator = 1;
    unsigned long position = 0;

    for(int i = 0; i<16384; i++){
        if((cluster & comparator) == 1){ position = i; break; }
    }

    return position;
}

Basically, i'm just troubling if the if condition is valid? Can i do the op '&' like that?

Was it helpful?

Solution

You need to change your comparator for each bit

unsigned long getFreeCluster()
{
  ...
  bool found = false;
  for (int i = 0; !found && (i < 2048); ++i)
    for (int b = 0; b < 8; ++b)
      if (cluster[i] & (1 << b) != 0)
      {
        position = i * 8 + b;
        found = true;
        break;
      }
}

If you are only looking for the first bit = 1, this might be faster:

unsigned long getFreeCluster()
{
  ...
  bool found = false;
  for (int i = 0; !found && (i < 2048); ++i)
    if (cluster[i] != 0)
      for (int b = 0; b < 8; ++b)
        if (cluster[i] & (1 << b) != 0)
        {
          position = i * 8 + b;
          break;
        }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top