' Bit Reverse — reverses bits in bytes using bitwise operators
#COMPILE EXE
#DIM ALL

FUNCTION PBMAIN() AS LONG
    LOCAL i AS LONG
    LOCAL j AS LONG
    LOCAL v AS LONG
    LOCAL r AS LONG
    LOCAL pow2(0 TO 7) AS LONG
    LOCAL rev2(0 TO 7) AS LONG

    pow2(0) = 1
    pow2(1) = 2
    pow2(2) = 4
    pow2(3) = 8
    pow2(4) = 16
    pow2(5) = 32
    pow2(6) = 64
    pow2(7) = 128
    rev2(0) = 128
    rev2(1) = 64
    rev2(2) = 32
    rev2(3) = 16
    rev2(4) = 8
    rev2(5) = 4
    rev2(6) = 2
    rev2(7) = 1

    PRINT "8-bit bit reversal"
    FOR i = 0 TO 31
        v = i * 8 + 3
        IF v > 255 THEN v = 255
        r = 0
        FOR j = 0 TO 7
            IF (v AND pow2(j)) <> 0 THEN
                r = r + rev2(j)
            END IF
        NEXT j
        PRINT HEX$(v) + " -> " + HEX$(r)
    NEXT i

    PRINT "Verification: reverse twice = original"
    FOR i = 0 TO 99
        v = i * 17 + 13
        IF v > 255 THEN v = v MOD 256
        r = 0
        FOR j = 0 TO 7
            IF (v AND pow2(j)) <> 0 THEN r = r + rev2(j)
        NEXT j
        v = r
        r = 0
        FOR j = 0 TO 7
            IF (v AND pow2(j)) <> 0 THEN r = r + rev2(j)
        NEXT j
    NEXT i
    PRINT "Done."

    FUNCTION = 0
END FUNCTION
