Delphi version of the BASE64 conversion function

Source: Internet
Author: User

Base64 is one of the most common encoding methods used to encrypt the transmission of 8Bit bytes of code on the network, online search, the code of. NET/C + + is everywhere, can not find Delphi, I wrote 2 functions, can be used for reference by visitors. (Note: Later, I think these 2 function flexibility is too poor, has been modified, see "Delphi version of the BASE64 conversion function (modified version)") unit Base64;

Interface

Uses sysutils;

function StrToBase64 (const str:string): string;
function base64tostr (const base64:string): string;

Implementation

Const
Base64_chars = ' abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz0123456789+/';

function StrToBase64 (const str:string): string;
Var
I, J, K, Len, Len1:integer;
b3:array[0:2] of Byte;
b4:array[0:3] of Byte;
Begin
If Str = "Then
Begin
Result: = ';
Exit;
End
Len: = Length (STR);
Len1: = ((Len + 2) div 3) SHL 2;
SetString (Result, Nil, Len1);
I: = 1;
J: = 1;
While I <= Len do
Begin
For K: = 0 to 2 do
If K + I > Len then b3[k]: = 0
else B3[k]: = Ord (Str[k + I]);
b4[0]: = b3[0] SHR 2;
b4[1]: = ((b3[0] SHL 4) or (b3[1] shr 4)) and 63;
b4[2]: = ((b3[1] SHL 2) or (b3[2] shr 6)) and 63;
b4[3]: = b3[2] and 63;
For K: = 0 to 3 do
Begin
Case B4[k] of
0..    25:RESULT[J]: = CHR (B4[k] + 65); ' A ' ... ' Z
26..   51:RESULT[J]: = CHR (B4[k] + 71); ' A ' ... ' Z ' (b4[k]-26+97)
62:RESULT[J]: = ' + ';
63:RESULT[J]: = '/';
else Result[j]: = CHR (B4[k]-4); ' 0 ' ... ' 9 ' (b4[k]-52+48)
End
RESULT[J]: = Base64_chars[b4[k] + 1];
INC (J);
End
INC (I, 3);
End
K: = 3-len mod 3-1;
If K <> 2 Then
For I: = Len1-k to Len1 do
Result[i]: = ' = ';
End

function base64tostr (const base64:string): string;
Var
I, J, K, Len, Len1:integer;
b4:array[0:3] of Byte;
Begin
If Base64 = "Then
Begin
Result: = ';
Exit;
End

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.