QB64 Phoenix Edition
Base-128 Encoding and Decoding - Printable Version

+- QB64 Phoenix Edition (https://qb64phoenix.com/forum)
+-- Forum: QB64 Rising (https://qb64phoenix.com/forum/forumdisplay.php?fid=1)
+--- Forum: Prolific Programmers (https://qb64phoenix.com/forum/forumdisplay.php?fid=26)
+---- Forum: SMcNeill (https://qb64phoenix.com/forum/forumdisplay.php?fid=29)
+---- Thread: Base-128 Encoding and Decoding (/showthread.php?tid=2028)



Base-128 Encoding and Decoding - SMcNeill - 09-23-2023

Code: (Select All)
_CONTROLCHR OFF

test$ = "abc"
a$ = B256to128$(test$)
b$ = B128to256$(a$)
PRINT test$, a$, b$
PRINT LEN(test$), LEN(a$), LEN(b$)

SLEEP

FOR i = 0 TO 255
    t$ = CHR$(i)
    PRINT i, t$,
    a$ = B256to128(t$)
    PRINT a$,
    b$ = B128to256(a$)
    PRINT b$
    IF t$ <> b$ THEN
        PRINT "DON'T MATCH!!"
        END
    END IF
NEXT

PRINT
PRINT "All characters match before and after encoding and decoding."



FUNCTION B256to128$ (text$)
    FOR i = 1 TO LEN(text$)
        a = ASC(text$, i) '                      get the ASCII value of our character
        b$ = RIGHT$("00000000" + _BIN$(a), 8) '  convert it to binary
        temp$ = temp$ + b$ '                      add the binary to a single long string
    NEXT
    padding$ = STRING$(7 - LEN(temp$) MOD 7, "0")
    temp$ = temp$ + padding$ '                    add necessay padding to make it suitable for base-128 encoding
    FOR i = 1 TO LEN(temp$) STEP 7
        c$ = MID$(temp$, i, 7) '                  get 7 characters from our 8 byte represention
        c = VAL("&B" + c$) '                      that's the character value of our base 128-character
        temp1$ = temp1$ + CHR$(c + 65) '              add that to our new string
    NEXT
    B256to128$ = temp1$
END FUNCTION

FUNCTION B128to256$ (text$)
    FOR i = 1 TO LEN(text$)
        a = ASC(text$, i) - 65
        b$ = RIGHT$("0000000" + _BIN$(a), 7)
        temp$ = temp$ + b$
    NEXT
    temp$ = LEFT$(temp$, 8 * INT(LEN(temp$) / 8)) 'remove padding
    FOR i = 1 TO LEN(temp$) STEP 8
        b$ = "&B" + MID$(temp$, i, 8)
        temp1$ = temp1$ + CHR$(VAL(b$))
    NEXT
    B128to256$ = temp1$
END FUNCTION