Base64 encoding and decoding

BlitzMax Forums/BlitzMax Programming/Base64 encoding and decoding

Been trying this by converting this to BMX but not having much luck. I'm assuming it's probably because of BMX's UTF16 string (and my stupidity of course), but before I go spending time on it I'm just wondering if anyone has done this already?

A quick hack job on some old BB routines. Changed just enough to work with BMax...

Print
Print "Many a mickle makes a muckle"

e$ = base64_enc("Many a mickle makes a muckle", 0)
Print e$

Print base64_dec(e$)
Print
End

' Encodes a String using the base64 algorithm
' inp$ = A String containing the data To be encoded
' add_nl = 1 - adds a newline seguence at the End of the encoded String, 0 - no newline (If String is < 76 chars)
' This Function returns a String containing the encoded data
' You shouldn't need to call this directly. But feel free.
Function base64_enc$(inp$, add_nl=1)
	Local b64_enc$ = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
	Local nl$ = Chr$(13) + Chr$(10)
	Local out$, trp$, char, i = 1
		
	Repeat
		trp$ = Mid$(inp$, i, 3)
	
		Select Len(trp$)
			Case 3
				out$ = out$ + Mid$(b64_enc$, (Asc(Mid$(trp$, 1, 1)) Shr 2) + 1, 1)
				out$ = out$ + Mid$(b64_enc$, (((Asc(Mid$(trp$, 1, 1)) Shl 4) | (Asc(Mid$(trp$, 2, 1)) Shr 4)) & $3f) + 1, 1)
				out$ = out$ + Mid$(b64_enc$, (((Asc(Mid$(trp$, 2, 1)) Shl 2) | (Asc(Mid$(trp$, 3, 1)) Shr 6)) & $3f) + 1, 1)
				out$ = out$ + Mid$(b64_enc$, (Asc(Mid$(trp$, 3, 1)) & $3f) + 1, 1)
			Case 2
				out$ = out$ + Mid$(b64_enc$, (Asc(Mid$(trp$, 1, 1)) Shr 2) + 1, 1)
				out$ = out$ + Mid$(b64_enc$, (((Asc(Mid$(trp$, 1, 1)) Shl 4) | (Asc(Mid$(trp$, 2, 1)) Shr 4)) & $3f) + 1, 1)
				out$ = out$ + Mid$(b64_enc$, ((Asc(Mid$(trp$, 2, 1)) Shl 2) & $3f) + 1, 1)
				out$ = out$ + "="
			Case 1
				out$ = out$ + Mid$(b64_enc$, (Asc(Mid$(trp$, 1, 1)) Shr 2) + 1, 1)
				out$ = out$ + Mid$(b64_enc$, ((Asc(Mid$(trp$, 1, 1)) Shl 4) & $3f) + 1, 1)
				out$ = out$ + "=="
		End Select
	
		i = i + 3
		char = char + 4
		If char = 76
			out$ = out$ + nl$
			char = 0
		EndIf
	Until i > Len(inp$)
	If char And add_nl Then out$ = out$ + nl$
	
	Return out$
End Function

' Decodes a String that's been encoded with the base64 algorithm
' inp$ = A String containing the encoded data
' This Function returns a String containing the decoded data
' You shouldn't need to call this directly. But feel free.
Function base64_dec$(inp$)
	Local b64_enc$ = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="
	Local out$, oct, i = 1, qc, char 

	Repeat
		char = Instr(b64_enc$, Mid$(inp$, i, 1))
		If char > 0
			If char = 65 Then char = 1
			oct = (oct Shl 6) | ((char - 1) & $3f)
			qc = qc + 1
		EndIf
		
		If qc = 4
			out$ = out$ + Chr$((oct Shr 16) & $ff) + Chr$((oct Shr 8) & $ff) + Chr$(oct & $ff)
			
			oct = 0
			qc = 0
		EndIf
	
		i = i + 1
	Until i > Len(inp$)
	
	Return out$
End Function


Thanking you very very much :-)