'----------------------------------------------------------------------------- ' Encode binary file data using Base64 encoding for MIME. ' Donated to the Public Domain by PowerBASIC, Inc. 08 January 2003. FUNCTION MimeEncode (BYVAL sFileData AS STRING) AS STRING LOCAL lBlock AS LONG LOCAL lcBlocks AS LONG LOCAL lByte1 AS LONG LOCAL lByte2 AS LONG LOCAL lByte3 AS LONG LOCAL lIndex1 AS LONG LOCAL lIndex2 AS LONG LOCAL lIndex3 AS LONG LOCAL lIndex4 AS LONG LOCAL pInput AS BYTE PTR LOCAL pOutput AS BYTE PTR LOCAL pTable AS BYTE PTR LOCAL sBase64 AS STRING LOCAL sResult AS STRING LOCAL Pad AS STRING ' Set up Base64 translation table sBase64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" ' Calculate padding for Base64 stream Pad = STRING$(2 - (LEN(sFileData) - 1) MOD 3, "=") ' Round up the length of the input data to a multiple of three lcBlocks = (LEN(sFileData) + 2) \ 3 IF lcBlocks * 3 > LEN(sFileData) THEN sFileData = LSET$(sFileData, lcBlocks * 3 USING $NUL) END IF ' Allocate the space for the output string sResult = SPACE$(lcBlocks * 4) ' Set up pointers so we can treat the data as byte streams pInput = STRPTR(sFileData) pOutput = STRPTR(sResult) pTable = STRPTR(sBase64) ' Loop through our entire input buffer FOR lBlock = 1 TO lcBlocks ' Get the next three binary data bytes to process lByte1 = @pInput INCR pInput lByte2 = @pInput INCR pInput lByte3 = @pInput INCR pInput ' Translate the three data bytes into four Base64 table indices lIndex1 = lByte1 \ 4 lIndex2 = (lByte1 AND 3) * 16 + lByte2 \ 16 lIndex3 = (lByte2 AND 15) * 4 + lByte3 \ 64 lIndex4 = lByte3 AND 63 ' Use the Base64 table to encode the output string @pOutput = @pTable[lIndex1] INCR pOutput @pOutput = @pTable[lIndex2] INCR pOutput @pOutput = @pTable[lIndex3] INCR pOutput @pOutput = @pTable[lIndex4] INCR pOutput NEXT ' Merge in the padding bytes RSET ABS sResult = Pad FUNCTION = sResult END FUNCTION