Not sure if I have this in the right category/forum but I have a problem with a line of code which I resolved but would like to understand why the original code didn't work as expected.
I believe the issue might be in the compiler rather than my code, though admittedly my original approach was poor.
using Arduino IDE 2.2.1 to write program for ESP32.
Board configured is ESP32 Dev Module
I have an array of 24 integers switchArray, where the integers are either 0 or 1 to represent an outlet being on or off.
I am generating another integer switchReg to represent each outlet as a bit in the integer, 8 at a time. Bank represents which group of 8 I am dealing with. Not relevant to the issue, but mentioned it since it is in the code.
Original code:
for(int outlet = 0 ; outlet <= 7 ; outlet++){
switchReg = switchReg<<1 + switchArray[bank*8 + outlet];
}
This had switchReg end up always resulting as 0.
Modification that worked:
for(int outlet = 0 ; outlet <= 7 ; outlet++){
switchReg = switchReg<<1 | switchArray[bank*8 + outlet];
}
T
his worked, where each of 8 bits properly represented the state of each outlet represented in the array.
Although it is bad form to mix bitwise manipulation with integer arithmetic, to me they should produce the same result since switchArray only contains 0 or 1 to represent if the outlet is or should be off or on so adding to the shifted switchReg 0 or 1 should have resulted the same as bitwise OR'ing the 0 or 1 to the rightmost bit of switchReg.
I discussed this with chatGPT, once we understood each other, we suspect the failure of the arithmetic approach may be compiler related.
Any ideas why the addition method ended up with results as 0?