AND for masking bits in Embedded C - Time & Space Complexity
We want to understand how the time it takes to mask bits using AND changes as the input size grows.
How does the number of operations grow when we apply AND to mask bits in data?
Analyze the time complexity of the following code snippet.
unsigned int mask_bits(unsigned int value, unsigned int mask) {
return value & mask;
}
void process_array(unsigned int *arr, unsigned int *masks, int n) {
for (int i = 0; i < n; i++) {
arr[i] = mask_bits(arr[i], masks[i]);
}
}
This code applies a bitwise AND mask to each element in an array of integers.
- Primary operation: The for-loop that applies the AND mask to each array element.
- How many times: It runs once for each element in the array, so n times.
As the array size grows, the number of AND operations grows directly with it.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 AND operations |
| 100 | 100 AND operations |
| 1000 | 1000 AND operations |
Pattern observation: The operations increase in a straight line as input size increases.
Time Complexity: O(n)
This means the time to mask bits grows directly with the number of elements you process.
[X] Wrong: "Masking bits with AND is always constant time no matter how many elements there are."
[OK] Correct: While one AND operation is constant time, doing it for many elements means the total time grows with the number of elements.
Understanding how simple bitwise operations scale helps you explain efficiency clearly and shows you know how loops affect performance.
"What if we nested the masking inside another loop that runs m times? How would the time complexity change?"