Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading