cbit-manipulationbytebit-shiftsliding-window

How do I create a sliding window of 5 bits in a single byte?


Here is a visual of what I want to have happen 5 bit sliding window

In words, I want a sliding window of 5 bits. I need to store a history of 5 events within a single byte. I'm using the 5 most significant bits to do this. The first time the event occurs I want to store that in bit 7 (most significant bit), the second time the event occurs, whether true or false, I want to store the latest event history in the 7th bit, and what was previously in bit 7 will slide over to bit 6. This will just keep repeating indefinitely, storing the latest event in bit 7 and sliding everything to the right, but only keeping 5 events.

Here is what I've tried so far, but I think my concept is pretty far off.

Edit: The for loop is just to imitate several loops of storing the history, so won't be used later on.

    unsigned char byte = 0;

    bool bit7 = true;
    bool bit6 = false;
    bool bit5 = true;
    bool bit4 = true;
    bool bit3 = false;

    // Set the individual bits in the byte
    byte |= (bit7 << 7);
    byte |= (bit6 << 6);
    byte |= (bit5 << 5);
    byte |= (bit4 << 4);
    byte |= (bit3 << 3);

    for (int i = 0; i <= 4; i++)
    {
        if (i == 0)
        {
            byte = bit7 << 7;
        }

        if (i == 1)
        {
            byte |= bit6 << 6;
        }

        if (i == 2)
        {
            byte |= bit5 << 5;
        }

        if (i == 3)
        {
            byte |= bit4 << 4;
        }

        if (i == 4)
        {
            byte |= bit3 << 3;
        }
    }

Solution

  • It is quite simple if I understand your task well

    uint8_t addevent(int event, uint8_t stored)
    {   
        stored >>= 1;
        stored |= (!!event) << 7;
    
        return stored;
    }