0
votes

I'm trying to fit 16, 32 and 64-bit values into an 8-bit container

I'm able to shift the bits to where it's only a 8 bits of data for the container, but I do not know how to bring them back to reflect the value. I've been racking my brain all day and I cannot figure it out. Any help would be so amazing. Here's the code I've been experimenting with before I start my lab project because this is the thing that has me confused. How would I store the 8 bits and then go back and be able to pull it back up without the lost bits

    #include <iostream>
    #include <stdio.h>
    #include <cstdint>

    using namespace std;

    int main()
    {

        const int MAX_SIZE = 1000;
        uint16_t data = 62153;
        uint8_t mem[MAX_SIZE];

        cout << data << endl;

        data = ( data >> 8) & 0xff;
        cout << data << endl;
        data = ( data << 8);
        cout << data << endl;
        return 0;
    }

output is:

1111 0010 1100 1001 = 62153

1111 0010 = 242 after bit shift

1111 0010 0000 0000 = 61952 shift back

those bits are gone, how can I save space by breaking up the bits to being able to store them in a smaller container, while still being able to have a function go back and read what the full value was before the shift. This is homework, so I'm not asking for an answer. A push in the right direction would be greatly appreciated.

1

1 Answers

0
votes

This should give you a push in A direction. You could also use a stack to achieve something similar. By using a vector you could determine what the output would be by checking the size of the vector. For example if the vector::size() == 2 you know you need to create a new uint16_t. If the vector size is 4 you need a uint32_t etc...

#include <vector>
#include <cstdint>
#include <iostream>

int main()
{
    std::vector<uint8_t> bytes;

    uint16_t data = 62153;
    uint8_t lsb = data & 0xff;
    uint8_t msb = (data >> 8) & 0xff;

    bytes.push_back(lsb);
    bytes.push_back(msb);

    uint16_t new_data = 0;
    new_data = new_data | (bytes.at(1) << 8);
    new_data = new_data | bytes.at(0);

    std::cout << new_data << std::endl;
    return 0;
}