M4BASIC - b64dec.m4b
Not logged in
REM Demo implementing BASE64 decoder
REM http://en.wikipedia.org/wiki/Base64
REM
REM Taken from the base64 decoder example of BaCon.
REM PvE, August 2014 - GPL.

STRING base1, base2, base3, base4, dat, decoded
INTEGER byte1, byte2, byte3, byte4

IF argc != 2 THEN
    PRINT "Usage: b64enc <string>" NL
    END
ENDIF

REM Get the string to convert
LET dat = argv[1]

REM the Base64 constant
CONST BASE64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"

WHILE LEN(dat) > 0 DO

    REM Specify byte values of incoming string
    SET base1 = MID(dat, 1, 1)
    SET base2 = MID(dat, 2, 1)
    SET base3 = MID(dat, 3, 1)
    SET base4 = MID(dat, 4, 1)

    REM Now find the indexnumber
    LET byte1 = INSTR(BASE64, base1) - 1
    IF byte1 < 0 THEN
        LET byte1 = 0
    ENDIF

    LET byte2 = INSTR(BASE64, base2) - 1
    IF byte2 < 0 THEN
        LET byte2 = 0
    ENDIF

    LET byte3 = INSTR(BASE64, base3) - 1
    IF byte3 < 0 THEN
        LET byte3 = 0
    ENDIF

    LET byte4 = INSTR(BASE64, base4) - 1
    IF byte4 < 0 THEN
        LET byte4 = 0
    ENDIF

    REM Recalculate to ASCII values
    SET decoded = CONCAT(decoded, CHR((byte1 & 63) * 4 + (byte2 & 48) / 16 ) )
    SET decoded = CONCAT(decoded, CHR((byte2 & 15) * 16 + (byte3 & 60) / 4 ) )
    SET decoded = CONCAT(decoded, CHR((byte3 & 3) * 64 + byte4 ) )

    REM Decrease incoming string with 4
    SET dat = RIGHT(dat, LEN(dat) - 4)

WEND

REM Print result
PRINT decoded NL

Return to M4BASIC