Can anyone suggest how I can write two functions: First one would allow me to push a single value but with a possibility to store a series of numbers in the range [0,1,2,3] inside a variable using bit integers.
The second function will retrieve whatever is stored in a value and return the maximum value because it might happen that all the values will be zero or a combination of zeros and any other values in the given list. When I call the second function if all the entries in the input value are zero, the function will return zero otherwise it returns the maximum value stored in the input variable as a value between 0 and 3. I will be grateful for any help.
some starting point:
#include <iostream>
usingnamespace std;
// Each value takes 2 bits, so a 64 bit value can hold up to 32 values.
// Precond: x >= 0 && x <= 3
void store(unsignedlong &n, unsigned x) {
n = (n << 2) | x;
}
unsigned get_max(unsignedlong n) {
unsigned m = 0;
for ( ; n; n >>= 2) if ((n & 3) > m) m = n & 3;
return m;
}
int main() {
unsignedlong n = 0;
for (int x: {1, 0, 2, 0, 0, 1}) store(n, x);
cout << "Max: " << get_max(n) << '\n';
}
@dutch Would you mind explaining the if condition in the get_max function? For instance, if now the upper limit of the list changes to 4 then n<<3 but how if would change? Thanks .
n & 3 "masks" out the lower 2 bits (since the binary of 3 is 11). To mask out the lower 3 bits you would use 7 (binary 111). With 3 bits you could store values from 0 to 7.