' 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" & FORMAT$(val, "&H") & ")"
        val = val SHL 1
    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, "&H") & ")"
    FOR i = 1 TO 8
        val = val SHR 1
        PRINT "SHR 1 = " & STR$(val) & "  (&H" & FORMAT$(val, "&H") & ")"
    NEXT i
    PRINT
END SUB

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

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

SUB RotateLeftDemo()
    LOCAL val AS DWORD
    LOCAL i AS LONG
    PRINT "=== ROTATE LEFT ==="
    val = &H80000001
    PRINT "Starting value: &H" & FORMAT$(val, "&H")
    FOR i = 1 TO 16
        val = ROTATE(val, 2)
        PRINT "ROTATE left 2: &H" & FORMAT$(val, "&H")
    NEXT i
    PRINT
END SUB

SUB RotateRightDemo()
    LOCAL val AS DWORD
    LOCAL i AS LONG
    PRINT "=== ROTATE RIGHT ==="
    val = &H000000FF
    PRINT "Starting value: &H" & FORMAT$(val, "&H")
    FOR i = 1 TO 8
        val = ROTATE(val, -4)
        PRINT "ROTATE right 4: &H" & FORMAT$(val, "&H")
    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
