' Checksum: CRC-32, Adler-32, sum8, sum16, XOR checksum
#COMPILE EXE
#DIM ALL

FUNCTION CRC32(BYVAL data AS STRING) AS LONG
    LOCAL i AS LONG
    LOCAL j AS LONG
    LOCAL crc AS LONG
    LOCAL b AS LONG
    LOCAL mask AS LONG
    crc = 4294967295
    FOR i = 1 TO LEN(data)
        b = ASC(MID$(data, i, 1))
        crc = crc XOR b
        FOR j = 1 TO 8
            mask = crc AND 1
            IF mask THEN
                crc = (crc / 2) XOR 3988292384
            ELSE
                crc = crc / 2
            END IF
        NEXT j
    NEXT i
    FUNCTION = crc XOR 4294967295
END FUNCTION

FUNCTION CRC32Hex(BYVAL data AS STRING) AS STRING
    FUNCTION = HEX$(CRC32(data), 8)
END FUNCTION

FUNCTION Adler32(BYVAL data AS STRING) AS LONG
    LOCAL i AS LONG
    LOCAL a AS LONG
    LOCAL b AS LONG
    a = 1
    b = 0
    FOR i = 1 TO LEN(data)
        a = (a + ASC(MID$(data, i, 1))) MOD 65521
        b = (b + a) MOD 65521
    NEXT i
    FUNCTION = (b * 65536) OR a
END FUNCTION

FUNCTION Adler32Hex(BYVAL data AS STRING) AS STRING
    FUNCTION = HEX$(Adler32(data), 8)
END FUNCTION

FUNCTION Sum8(BYVAL data AS STRING) AS LONG
    LOCAL i AS LONG
    LOCAL sum AS LONG
    FOR i = 1 TO LEN(data)
        sum = (sum + ASC(MID$(data, i, 1))) AND 255
    NEXT i
    FUNCTION = sum
END FUNCTION

FUNCTION Sum16(BYVAL data AS STRING) AS LONG
    LOCAL i AS LONG
    LOCAL sum AS LONG
    FOR i = 1 TO LEN(data)
        sum = (sum + ASC(MID$(data, i, 1))) AND 65535
    NEXT i
    FUNCTION = sum
END FUNCTION

FUNCTION XORSum(BYVAL data AS STRING) AS LONG
    LOCAL i AS LONG
    LOCAL x AS LONG
    FOR i = 1 TO LEN(data)
        x = x XOR ASC(MID$(data, i, 1))
    NEXT i
    FUNCTION = x AND 255
END FUNCTION

FUNCTION PBMAIN() AS LONG
    PRINT "=== Checksum Functions ==="
    PRINT
    PRINT "CRC-32 checksums:"
    PRINT "  'Hello World': 0x" & CRC32Hex("Hello World")
    PRINT "  'The quick brown fox jumps over the lazy dog': 0x" & CRC32Hex("The quick brown fox jumps over the lazy dog")
    PRINT "  'PBXB64 Compiler': 0x" & CRC32Hex("PBXB64 Compiler")
    PRINT "  '' (empty): 0x" & CRC32Hex("")
    PRINT
    PRINT "Adler-32 checksums:"
    PRINT "  'Hello World': 0x" & Adler32Hex("Hello World")
    PRINT "  'PBXB64': 0x" & Adler32Hex("PBXB64")
    PRINT "  '' (empty): 0x" & Adler32Hex("")
    PRINT
    PRINT "Simple checksums for 'Hello World':"
    PRINT "  Sum8: " & FORMAT$(Sum8("Hello World"))
    PRINT "  Sum16: " & FORMAT$(Sum16("Hello World"))
    PRINT "  XOR: " & FORMAT$(XORSum("Hello World"))
    PRINT
    PRINT "Verify CRC-32: "
    IF CRC32("Hello World") = CRC32("Hello World") THEN PRINT "  Same string: PASS"
    IF CRC32("Hello") <> CRC32("World") THEN PRINT "  Different: PASS"
    PRINT
    PRINT "Checksum tests complete."
    FUNCTION = 0
END FUNCTION
