How to access a bit within a byte in a FOR loop

Hello, So I understand I can directly access the bit of a byte. Example below will access first bit within the TESTBYTE IF TESTBYTE.X0 THEN … END_IF However, let’s say I wanted to write a FOR loop to more efficiently cycle through an array of byte(s) and copy over the data into a destination byte… Example: FOR i := 0 TO 7 BY 1 DO IF BYTEINPUT[2].X[i] THEN BYTESTORAGE.X[i] := TRUE; END_IF END_FOR So this gives me an error as it does not like the ~.X[i] parameter. I’ve tried ~.Xi , ~%i Nothing seems to work. Is this possible or do I have to hard code an IF statement for each bit I want to access? Thank you,

I’m fairly sure it’s only possible to use variable access to arrays, so unfortunately what you’re trying is not possible in that way. One alternative might be to shift the bits to the right, one place, at the end of each loop, using the SHR function. Then you can check the least significant bit (.X0) on every loop. FOR i := 0 TO 7 DO BYTESTORAGE.X7 := BYTEINPUT[2].X0; BYTESTORAGE := SHR(BYTESTORAGE, 1); BYTEINPUT[2] := SHR(BYTEINPUT[2], 1); END_FOR (of course in my example you could simply assign the whole byte - BYTESTORAGE := BYTEINPUT[2] - but I guess you are doing something different). Hope this helps.

Or perhaps I am overlooking the most obvious solution. Can I not just say: BYTESTORAGE : = BYTEINPUT[2]; Since I am just copying one byte to another?

Thanks, I believe your post edit and my second post came to the same realization… this is why I should be sleeping instead of programming at 2:30 am :stuck_out_tongue:

Writing the entire byte is the better way to go here, but in case anyone else comes up with the question of how to do dynamic bit access within a word: I would use the GET_BIT and SET_BIT functions. Using your first question as the example: FOR i := 0 TO 7 DO IF GET_BIT(BYTEINPUT[2], i) THEN BYTESTORAGE := SET_BIT(BYTESTORAGE, i); END_IF END_FOR

Nice one Rob H.