Search code examples
cbyte-shifting

C - Walking one and zero test, rotating through carry


I am a student, a couple of years messing about with C but no solid period of practising the language. I am trying to perform a walking one and walking zero test on a byte and pretty stuck, any tips would be appreciated.

I have two questions.

1) How do I perform a walking Zero?

2) How do I perform a rotate right through carry (or left) in C?

I worked out a walking one bit of code, although this does not carry round and restart at bit 0

int8_t walkOne = 1;
walkOne <<= 1;

Walking Zero: ??

I know there must be a better way of doing this is anyone able to help?

Regards


Solution

  • C does not provide any rotate operation. However, you do not need one for this. To prepare the walking-one value for step i, simply shift a one bit by i % 8 bits:

    uint8_t walkOne = 1u << i%8;
    

    i%8 is the remainder when i is divided by eight.

    For walking zeroes, complement the pattern:

    uint8_t walkZero = ~(1u << i%8);