Writing Base64
We have seen how to decode base64 now lets see how to encode base64....
This is pretty much a reverse of the decode function with a couple of exceptions. Then base64char function just does a lookup on a number for the corresponding character in the table.
All we do is loop throuugh the raw string data in groups of three obviously at the end if the source data is not a multiple of 3 we will buffer with the padding character ''=".
With each group of three bytes (24 bits) we transform that into four 6 bit characters from our limited character set..
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
and the padding char =.
Here is the code:
Base64encode
oString = ''
BytesLeft# = LEN(CLIP(lString))
LOOP i# = 1 TO LEN(CLIP(lString)) BY 3
IF BytesLeft# = 1 THEN
BigNumber# = BSHIFT(VAL(lString[i#]),16)
Char1# = BAND(BSHIFT(BigNumber#,-18),111111b)
Char2# = BAND(BSHIFT(BigNumber#,-12),111111b)
oString = LEFT(CLIP(oString)) & base64char(Char1#)&base64char(Char2#)&'=='
ELSIF BytesLeft# = 2 THEN
BigNumber# = BSHIFT(VAL(lString[i#]),16) + BSHIFT(VAL(lString[i# + 1]),8)
Char1# = BAND(BSHIFT(BigNumber#,-18),111111b)
Char2# = BAND(BSHIFT(BigNumber#,-12),111111b)
Char3# = BAND(BSHIFT(BigNumber#,-6),111111b)
oString = LEFT(CLIP(oString)) & base64char(Char1#)&base64char(Char2#)&base64char(Char3#)&'='
ELSE
BigNumber# = BSHIFT(VAL(lString[i#]),16) + BSHIFT(VAL(lString[i# + 1]),8) + VAL(lString[i# + 2])
Char1# = BAND(BSHIFT(BigNumber#,-18),111111b)
Char2# = BAND(BSHIFT(BigNumber#,-12),111111b)
Char3# = BAND(BSHIFT(BigNumber#,-6),111111b)
Char4# = BAND(BigNumber#,111111b)
oString = LEFT(CLIP(oString)) & base64char(Char1#)&base64char(Char2#)&base64char(Char3#)&base64char(Char4#)
END
IF BytesLeft# <= 3 THEN BREAK.
BytesLeft# -= 3
END
RETURN LEFT(CLIP(oString))Enjoy....obvioulsy this code could be improved. Currenlty it is limited to 4Mb and it involves repeated clips of a large string....til next time
