' Shift & Rotate — SHL, SHR, bit patterns
#COMPILE EXE
#DIM ALL

SUB ShiftLeftDemo()
    LOCAL i AS LONG
    LOCAL val AS DWORD
    PRINT "=== SHIFT LEFT ==="
    val = 1
    FOR i = 0 TO 8
        PRINT "1 SHL " & STR$(i) & " = " & STR$(val) & "  (&H" & STR$(val) & ")"
        val = val * 2
    NEXT i
    PRINT
END SUB

SUB ShiftRightDemo()
    LOCAL i AS LONG
    LOCAL val AS DWORD
    PRINT "=== SHIFT RIGHT ==="
    val = &HFF00
    PRINT "Original: " & STR$(val) & "  (&H" & FORMAT$(val) & ")"
    FOR i = 1 TO 8
        val = val \ 2
        PRINT "SHR 1 = " & STR$(val) & "  (&H" & FORMAT$(val) & ")"
    NEXT i
    PRINT
END SUB

SUB MultiplyDivideByShift()
    LOCAL i AS LONG
    LOCAL val AS LONG
    LOCAL pow2 AS LONG
    PRINT "=== MULTIPLY/DIVIDE BY SHIFT ==="
    val = 5
    pow2 = 2
    FOR i = 1 TO 5
        PRINT STR$(val) & " * " & STR$(pow2) & " = " & STR$((val * pow2)) & "  (shift left " & STR$(i) & ")"
        pow2 = pow2 * 2
    NEXT i
    PRINT
    val = 1024
    pow2 = 2
    FOR i = 1 TO 5
        PRINT STR$(val) & " / " & STR$(pow2) & " = " & STR$((val \ pow2)) & "  (shift right " & STR$(i) & ")"
        pow2 = pow2 * 2
    NEXT i
    PRINT
END SUB

SUB BitPatternGenerator()
    LOCAL i AS LONG
    LOCAL j AS LONG
    LOCAL pat AS LONG
    LOCAL pow2 AS LONG
    PRINT "=== BIT PATTERN GENERATOR ==="
    FOR i = 0 TO 7
        pat = 0
        pow2 = 1
        FOR j = 0 TO 7
            IF (i + j) MOD 2 = 0 THEN
                pat = pat OR pow2
            END IF
            pow2 = pow2 * 2
        NEXT j
        PRINT "Pattern " & STR$(i) & ": " & STR$(pat)
    NEXT i
    PRINT
END SUB

SUB RotateLeftDemo()
    LOCAL val AS LONG
    LOCAL i AS LONG
    LOCAL t AS LONG
    PRINT "=== ROTATE LEFT (simulated) ==="
    val = 1
    PRINT "Starting value: " & STR$(val)
    FOR i = 1 TO 16
        t = val
        val = t * 2
        PRINT "SHL " & STR$(i) & ": " & STR$(val)
    NEXT i
    PRINT
END SUB

SUB RotateRightDemo()
    LOCAL val AS LONG
    LOCAL i AS LONG
    PRINT "=== ROTATE RIGHT (simulated) ==="
    val = 65536
    PRINT "Starting value: " & STR$(val)
    FOR i = 1 TO 8
        val = val \ 2
        PRINT "SHR " & STR$(i) & ": " & STR$(val)
    NEXT i
    PRINT
END SUB

SUB PowerOfTwoCheck()
    LOCAL i AS LONG
    LOCAL n AS LONG
    PRINT "=== POWER OF 2 CHECK ==="
    FOR i = 1 TO 16
        n = i
        IF n > 0 AND (n AND (n - 1)) = 0 THEN
            PRINT STR$(n) & " is a power of 2"
        ELSE
            PRINT STR$(n) & " is NOT a power of 2"
        END IF
    NEXT i
    PRINT
END SUB

FUNCTION PBMAIN() AS LONG
    PRINT "==========================="
    PRINT " Shift & Rotate Operations"
    PRINT "==========================="
    PRINT
    CALL ShiftLeftDemo()
    CALL ShiftRightDemo()
    CALL MultiplyDivideByShift()
    CALL BitPatternGenerator()
    CALL RotateLeftDemo()
    CALL RotateRightDemo()
    CALL PowerOfTwoCheck()
    PRINT "Shift/rotate demos complete."
    FUNCTION = 0
END FUNCTION
