Situation: A light switch can either be ON or OFF.
If 'ON' = 1 and 'OFF' = 0, what is the optimal way to program a 'toggle' effect?
so: if I start with '0' and hit the spacebar, my '0' becomes '1'.
if I hit the spacebar again, my '1' goes back to being '0'. And so on.
The following is a working program that demonstrates the idea, but it's not optimal. The challenge is to optimize & simplify the program for the same output.
' ======================= ONLY an EXAMPLE not an ENTRY ============
counter% = 0
toggle% = 1
WHILE k$ <> CHR$(27)
k$ = INKEY$
IF k$ = CHR$(32) THEN
counter% = counter% + 1
IF counter% / 2 = counter% \ 2 THEN toggle% = 0 ELSE toggle% = 1
PRINT toggle%
END IF
As ChronoKitsune showed, XOR is great for toggling specific individuals bits. If, instead, you want to toggle all the bits (for example: 0 to -1 to 0), you could use NOT.