Advanced
Bit Manipulation
Advanced bit tricks with only AND, NOT, and ADD.
Bitwise Operations in LC-3
With only AND, NOT, and ADD, we can still perform all common bit operations.
OR (using De Morgan's Law)
A OR B = NOT(NOT(A) AND NOT(B)); R2 = R0 OR R1
NOT R3, R0 ; R3 = ~R0
NOT R4, R1 ; R4 = ~R1
AND R2, R3, R4 ; R2 = ~R0 & ~R1
NOT R2, R2 ; R2 = ~(~R0 & ~R1) = R0 | R1XOR
A XOR B = (A AND NOT(B)) OR (NOT(A) AND B); R2 = R0 XOR R1
NOT R3, R1 ; R3 = ~R1
AND R3, R0, R3 ; R3 = R0 & ~R1
NOT R4, R0 ; R4 = ~R0
AND R4, R4, R1 ; R4 = ~R0 & R1
; Now OR them: R2 = R3 | R4
NOT R3, R3
NOT R4, R4
AND R2, R3, R4
NOT R2, R2 ; R2 = R0 XOR R1Shift Left (Multiply by 2)
LC-3 has no shift instruction, but ADD R0, R0, R0 effectively doubles the value — which is a left shift by 1 bit.
; Shift R0 left by 3 positions (multiply by 8)
ADD R0, R0, R0 ; R0 << 1
ADD R0, R0, R0 ; R0 << 2
ADD R0, R0, R0 ; R0 << 3Testing a Specific Bit
To check if bit N of R0 is set, AND with a mask that has only bit N set:
; Test if bit 0 (LSB) of R0 is set
AND R1, R0, #1 ; R1 = R0 & 1
BRp BIT_IS_SET ; If result > 0, bit was set
; Test if bit 4 is set — need value 16 = 0x10
AND R2, R2, #0
ADD R2, R2, #1
ADD R2, R2, R2 ; 2
ADD R2, R2, R2 ; 4
ADD R2, R2, R2 ; 8
ADD R2, R2, R2 ; 16
AND R1, R0, R2 ; R1 = R0 & 16
BRp BIT4_SETExercise
Write a program that counts the number of 1-bits in a value. Load the value from memory (use x00FF = 255 which has 8 set bits), count the bits, and print the count as a digit.
1
R0
x00000
R1
x00000
R2
x00000
R3
x00000
R4
x00000
R5
x00000
R6
x00000
R7
x00000
PCx3000
CC
NZP