Search code examples
cpic

C programming Bitwise operator &= struggling to understand what its doing


I am trying to work out how this part of this code is working. REF state &= 0X07;

static uint8_t state = 0;
    /*  values for half step             0001, 0011, 0010, 0110, 0100, 1100, 1000, 1001*/
    static const uint8_t HalfSteps[8] = {0x01, 0x03, 0x02, 0x06, 0x04, 0x0C, 0x08, 0x09};
    uint8_t delay;

    do
    {
        if (Count > 0)
        {
            PORTC = HalfSteps[state];   /* drive stepper to select state */
            state++;                    /* step one state clockwise */
            state &= 0x07;              /* keep state within HalfStep table */
            Count--;   

The part after the state++ will increase from start of 0 and I know its resetting to 0 after goes above 7.

But not sure how this is achieved I have read that it basically means.

state = state + 7 but that does not look right.

Any easy explanations would be appreciated.


Solution

  • The following three lines are all equivalent:

    state &= 0x07;
    state = state & 7;
    state = state % 8;
    

    The effect is to ensure that the state is always less than 8, and also that the state that comes after 7 is 0, not 8.