return maximum value saved as a series of values turn to bits

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:
1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>

using namespace std;
unsigned long store(int data){
    unsigned long packit =  (packit << 2) | data;
    return packit
}

unsigned int MaxRetrieve(unsigned long packit){
    unsigned int output = ((packit >> (4*(which-1))) & 0xFF);
    return output
}
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
using namespace std;

// Each value takes 2 bits, so a 64 bit value can hold up to 32 values.
// Precond: x >= 0 && x <= 3
void store(unsigned long &n, unsigned x) {
    n = (n << 2) | x;
}

unsigned get_max(unsigned long n) {
    unsigned m = 0;
    for ( ; n; n >>= 2) if ((n & 3) > m) m = n & 3;
    return m;
}

int main() {
    unsigned long 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 .
Last edited on
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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <iostream>
using namespace std;

const unsigned BitsPerValue = 3;
const unsigned Mask = (1u << BitsPerValue) - 1;

// Precond: x >= 0 && x <= Mask
void store(unsigned long &n, unsigned x) {
    n = (n << BitsPerValue) | x;
}

unsigned get_max(unsigned long n) {
    unsigned m = 0;
    for ( ; n; n >>= BitsPerValue)
        if ((n & Mask) > m)
            m = n & Mask;
    return m;
}

int main() {
    unsigned long n = 0;
    for (int x: {3, 1, 3, 0, 2, 4, 2, 1})
        store(n, x);
    cout << "Max: " << get_max(n) << '\n';
}

@dutch Thanks for the explanation. It was very helpful. :)
Last edited on
Topic archived. No new replies allowed.