yhf8377
yhf8377

Reputation: 270

In-place bitwise AND then restore original value

I have a tight memory restriction where I am not allowed to allocate heap memory nor use local variables on stack for the following bit operation.

I have two integer values A and B (let's say they are just two byte values). I want to know what is the result of A & B (for example by A &= B) and then restore the original value of A into A.

As no extra memory is allowed, I can not temporarily store A's original value. Can I simply use a sequence of bit operation to restore A's value?

The reason for this is I have a big array of data where I need to count the bits after I bitwise-and something to it. But I need to retain the original value to test them against other values. The actual data is on a device where heap allocation is very expensive. And the data is dynamic in length so I can not declare a local variable to hold its temporary value.

Is this possible? If so how should I do it?

Upvotes: 1

Views: 477

Answers (1)

dbush
dbush

Reputation: 223699

You seem to be under the impression that you need to make a copy of the entire array, modify the copy, then perform operations on it. That isn't necessary.

For each element of the array, calucate A & B and store it in a local. Then count the number of bits set, and add that to a running total.

For example:

int count_bits_with_and(unsigned char *array, int size, unsigned char val)
{
    int i, sum;

    for (i=0, sum=0; i<size; i++) {
        unsigned char v = array[i] & val;
        int count = count_bits(v);
        sum += count;
    }
    return sum;
}

Upvotes: 1

Related Questions