It can be useful to encode a text string into a base 64 representation. For example when passing usernames and passwords to an SMTP server the request and response are both done using base 64.
The encoding is done by taking 3 ASCII values to form a 24bit binary value end then splitting this into 6 bit chunks starting from the left hand side. If there are less then 3 characters at the end then we pad out with zeroes and add one or 2 == signs to the end of the Base64 string
REM Base 64 Endode and Decode INPUT "Enter String to be encoded:" input$ A$ = FNEncode64(input$) PRINT A$ B$=FNDecode64(A$) PRINT B$ END
The program uses the following Function to encode the input string and return the Base64 Encoded Text
REM Function to Encode a string into Base64 DEF FNEncode64(text$) enc$="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" REM Get length of input string len=LEN(text$) output$="" count1 = 1 WHILE (count1 <= len) in%=0 REM This will hold up to 3 input characters as an integer count2=0 REM Get next 3 characters - or however many remains in the string as appropriate REPEAT in%=in% << 8 REM Shift bits 8 places to the left (same as multiplying by 256) in%=in%+ASC(MID$(text$,(count1+count2),1)) REM Add ASCII Value of Character count2 += 1 UNTIL(count2=3 OR ((count1+count2)>len)) in%=in%<<(8*(3-count2)) REM Pad with zeroes if we have less than 3 bytes to make a 24 bit number FOR n=1 TO 4 output$+= MID$(enc$, (in%>>18)+1,1) in% = (in% << 6) AND &FFFFFF REM move next 6 binary digits into position NEXT n IF (count2=1) THEN RIGHT$(output$,2)="==" ELSEIF (count2=2) THEN RIGHT$(output$)="=" count1 += 3 ENDWHILE =output$
And also this function to Decode a Base64 string back to a standard ASCII String
REM Function to decode a Base64 string into ASCII DEF FNDecode64(B64$) enc$="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" output$="" padding=0 len=LEN B64$ REM because of the padding character = at the end of the encoded text, the base 64 string length will always be a multiple of 4 FOR pos=1 TO len STEP 4 in%=0 REM Get the next 4 Characters and convert to a 24 bit number FOR pos2=0 TO 3 out%=0 in%=in%<<6 IF MID$(B64$,pos+pos2,1)="=" THEN padding=padding+1 ELSE out%=INSTR(enc$, MID$(B64$,pos+pos2,1))-1 in%=in%+out% ENDIF NEXT REM Now we have a 24 bit value we break it down into up to 3 8 bit chunks FOR n = 1 TO (3-padding) out%=in% >>16 output$=output$+CHR$(out%) in%=(in%<<8) AND &FFFFFF REM Shift next 8 bits into position NEXT NEXT =output$