' Endian conversion: big/little-endian swapped, 16/32-bit, detection
#COMPILE EXE
#DIM ALL

FUNCTION PBMAIN() AS LONG
    LOCAL v AS LONG
    LOCAL buf AS STRING
    LOCAL i AS LONG
    LOCAL b0 AS LONG
    LOCAL b1 AS LONG
    LOCAL b2 AS LONG
    LOCAL b3 AS LONG
    LOCAL swapped AS LONG
    LOCAL testVal AS LONG
    LOCAL s AS STRING

    PRINT "=== Endian Conversion ==="
    PRINT

    testVal = 1
    s = MKD$(testVal)
    IF ASC(LEFT$(s, 1)) = 1 THEN PRINT "System: Little-Endian" ELSE PRINT "System: Big-Endian"
    PRINT

    v = 305419896
    b0 = v MOD 256
    b1 = (v / 256) MOD 256
    b2 = (v / 65536) MOD 256
    b3 = (v / 16777216) MOD 256
    swapped = b0 * 16777216 + b1 * 65536 + b2 * 256 + b3
    PRINT "DWord 305419896 swappedped: " & FORMAT$(swapped)
    b0 = swapped MOD 256
    b1 = (swapped / 256) MOD 256
    b2 = (swapped / 65536) MOD 256
    b3 = (swapped / 16777216) MOD 256
    swapped = b0 * 16777216 + b1 * 65536 + b2 * 256 + b3
    PRINT "Swap again: " & FORMAT$(swapped)
    PRINT

    buf = SPACE$(8)
    v = 3735928559
    b0 = (v / 16777216) AND 255
    b1 = (v / 65536) AND 255
    b2 = (v / 256) AND 255
    b3 = v AND 255
    MID$(buf, 1, 1) = CHR$(b0)
    MID$(buf, 2, 1) = CHR$(b1)
    MID$(buf, 3, 1) = CHR$(b2)
    MID$(buf, 4, 1) = CHR$(b3)
    v = 3405691582
    b0 = (v / 16777216) AND 255
    b1 = (v / 65536) AND 255
    b2 = (v / 256) AND 255
    b3 = v AND 255
    MID$(buf, 5, 1) = CHR$(b0)
    MID$(buf, 6, 1) = CHR$(b1)
    MID$(buf, 7, 1) = CHR$(b2)
    MID$(buf, 8, 1) = CHR$(b3)

    PRINT "Big-endian buffer bytes:"
    FOR i = 1 TO 8
        PRINT RIGHT$("0" & HEX$(ASC(MID$(buf, i))), 2)
    NEXT i
    PRINT

    b0 = ASC(MID$(buf, 1, 1))
    b1 = ASC(MID$(buf, 2, 1))
    b2 = ASC(MID$(buf, 3, 1))
    b3 = ASC(MID$(buf, 4, 1))
    PRINT "Read BE at 1: " & FORMAT$(b0 * 16777216 + b1 * 65536 + b2 * 256 + b3)
    b0 = ASC(MID$(buf, 5, 1))
    b1 = ASC(MID$(buf, 6, 1))
    b2 = ASC(MID$(buf, 7, 1))
    b3 = ASC(MID$(buf, 8, 1))
    PRINT "Read BE at 5: " & FORMAT$(b0 * 16777216 + b1 * 65536 + b2 * 256 + b3)
    PRINT

    PRINT "Endian conversion tests complete."
    FUNCTION = 0
END FUNCTION
