0

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

MBK
  • 13
  • 6
  • 3
    Walking Zero: invert the result of walking one using operator `~`. – Stephan Lechner Jan 15 '19 at 11:09
  • 3
    BTW: with bit shifting, use unsigned data types to avoid undefined behaviour when shifting into some sort of "signed bit". – Stephan Lechner Jan 15 '19 at 11:10
  • Thank you, makes sense can't believe I did not think of that – MBK Jan 15 '19 at 11:17
  • Walking zero as in just moving a zero through a byte? Or walking zero as a way to test RAM cells? The latter is rather intricate, but usually what walking zero/one refers to. – Lundin Jan 15 '19 at 11:51
  • Just moving a zero through a byte, more like testing a variable that is linked to a bunch of switches and making sure 2 lines are not connected together – MBK Jan 15 '19 at 12:13
  • C has no concept of "carry flag". Do you need to simulate the behaviour of typical carry flag, with `bool carry` variable or something? – hyde Jan 15 '19 at 13:58
  • Hi Hyde, no I have just been doing a lot of assembler recently and wondered if C had any sort of alternative. This was just a grey area, after doing the task in assembler I wondered how it could be done in C – MBK Jan 15 '19 at 19:56
  • @MBK Yeah, if you want a shift with carry, you have to extract the desired bit as separate step before shift. Also if you want to rotate bits (instead of shift), you have to extract the part that wraps over, shift the other way and OR the parts together. You can't really do arithmetic with overflow on signed integers at all (it is Undefined Behaviour), and with unsigned integers you have to explicitly test if there was overflow and value was wrapped over. A good compiler will still optimise it to the correct single CPU instruction, if it recognises what you are trying to do. – hyde Jan 17 '19 at 11:21

1 Answers1

0

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);
Eric Postpischil
  • 195,579
  • 13
  • 168
  • 312