16-bit Unsigned AND on Commodore 64
By Michael Doornbos
- 2 minutes read - 336 wordsI have a project that requires something beyond the default BASIC that’s available on the Commodore 8-bit computers. Actually, it’s several things.
- 16-bit AND for unsigned integers
- XOR
- Decimal to Hex
- Hex to Decimal
I can get two of these by utilizing Simon’s BASIC Cart: XOR and Hex to Decimal.
Today, we’re going to implement a 16-bit unsigned AND .
In Commodore 64 BASIC V2, the AND
operator works with 16-bit signed integers (-32768 to +32767).
If we try to AND two unsigned 16-bit integers, we get an overflow

Use Two’s Complement for Values > 32767
For unsigned values above 32767, you can treat them as their signed equivalents in two’s complement, since the bitwise AND
operation is identical for signed and unsigned interpretations of the same bit pattern.
How it works
- If a value is > 32767, convert it to its signed equivalent:
value - 65536
. - Perform the
AND
operation. - If the result is negative, convert back to unsigned:
result + 65536
.
10 A=40000: B=50000
20 IF A>32767 THEN A=A-65536
30 IF B>32767 THEN B=B-65536
40 C=A AND B
50 IF C<0 THEN C=C+65536
60 PRINT C
40000
→40000 - 65536 = -25536
(signed).50000
→50000 - 65536 = -15536
(signed).-25536 AND -15536
=-32704
(signed).- Convert back:
-32704 + 65536 = 32832
(unsigned). - Final Answer:
32832
.

For more on Two’s compliment, we’ve talked about it before.
Extra credit - Assembly preview
Here’s a little preview of how we’ll do 16-bit AND
in Assembly in a later article.
; MEMORY LOCATIONS:
; $FB-$FC = FIRST 16-BIT VALUE (A)
; $FD-$FE = SECOND 16-BIT VALUE (B)
; $F7-$F8 = RESULT OF 16-BIT AND OPERATION
* = $C000 ; START AT MEMORY ADDRESS $C000 (49152)
LDA $FB ; LOAD LOW BYTE OF A
AND $FD ; AND WITH LOW BYTE OF B
STA $F7 ; STORE RESULT LOW BYTE
LDA $FC ; LOAD HIGH BYTE OF A
AND $FE ; AND WITH HIGH BYTE OF B
STA $F8 ; STORE RESULT HIGH BYTE
RTS
- Code
- How-To
- Retro
- Programming
- Tutorial
- Basics
- Assembly
- C64
- Commodore
- Unsigned
- AND
- Bitwise
- Two's Complement