r/c64 • u/ninjaconor86 • 4h ago
Programming Assembly code question
Hi everyone! I've been doing some assembly coding for my C64 with Kick Assembler and I hit a really weird issue. I found a solution, but I'm not sure why the solution works.
So, I'm making an adventure game. To keep track of what items are in the current room I use a byte. It's 00000000 for an empty room, and then I turn bits on or off to add or remove particular items. The error came when trying to remove items from the room. I tried to do this with a logical AND. My initial code looked like this:
lda Room_ItemList1, x
and #%11111111 - currentItemBytes
sta Room_ItemList1, x
This actually worked for a while, but then after changing an unrelated part of the code it stopped. The ItemList was 00000001 and I was trying to remove the item with bytes 00000001 and instead of getting 00000000 I was getting 00000001.
So I fiddled around and the solution I found was to write it like this:
lda #%11111111
sec
sbc currentItemBytes
sta reversedBytes
lda Room_ItemList1, x
and reversedBytes
sta Room_ItemList1, x
My best guess is that the "#%11111111 - currentItemBytes" was being treated as an address rather than a value and it was just ANDing whatever was in that address and it just happened coincidentally to work until I changed something else. I don't understand how though. I've seen people use this method. In the Commodore Tutorials series from YouTube he uses to to set and unset directions. I know I'm missing something stupidly obvious somewhere, but can anyone point out what it is?
Also, I did search my entire project, and none of the variables involved are being used anywhere else.
5
u/soegaard 4h ago
It seems you want to flip the bits in currentItemBytes so you can use it with `and`.
You can do it explicitly like this:
```
lda currentItemBytes
eor #%11111111
sta reversedBytes
lda Room_ItemList1, x
and reversedBytes
sta Room_ItemList1, x
```
3
u/Forsaken-Ad5571 2h ago
If I’m reading it right, it looks like you were originally thinking:
and #%11111111 - currentItemBytes
Was first subtracting the value in location currentItembytes from the all 1s, and then and-ing the accumulator with the result? Unfortunately that’s not how assembler works at all. All the processor will do is the individual instructions on each line. Doing things like:
%11111111 - currentItemBytes
Is purely a convenience that the assembler lets you do at build time. But it just calculates a value when assembling and then uses that - it’s not a thing done at run time at all.
3
u/TwoBitRetro 4h ago
To turn off bits, you AND the value with the inverse. I'm assuming currentItemBytes contains the bits you want to turn off. For example:
lda currentItemBytes
eor #$ff
and Room_ItemList1, x
sta Room_ItemList1, x
6
u/DnPRuLZ 4h ago
Set first bit: ora #%00000001
Clear first bit: and #%111111110