字符转换为Base64编码
代码
function strtoBase64(str:string):string;
var
_1byte,_2byte:array of byte;
strlen,i,j,jj:integer;
const
basetable='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
begin
//str:='xxc';
//str:='abcabc';
strlen:=length(str);
setlength(_1byte,strlen);
if strlen mod 3 >0 then setlength(_2byte,((strlen div 3) * 4 + strlen mod 3)+1)
else setlength(_2byte,(strlen div 3)*4+(strlen mod 3)+0);
for i:=0 to strlen-1 do
begin
_1byte[i]:=ord(str[i+1]);
end;
j:=0;
jj:=0;
for i:=0 to (strlen div 3)-1 do
begin
j:=i*3;
_2byte[jj]:=_1byte[j] shr(2); //a->A;
inc(jj);
_2byte[jj]:=byte(_1byte[j] shl(6)) shr(2) + _1byte[j+1] shr(4); //a&b->B
inc(jj);
_2byte[jj]:=byte(_1byte[j+1] shl(4)) shr(2)+_1byte[j+2]shr(6); //b&c->C
inc(jj);
_2byte[jj]:=byte(_1byte[j+2] shl(2))shr(2);
inc(jj);
end;
j:=(strlen div 3)*3;
case (strlen mod 3) of
1:
begin
_2byte[jj]:=_1byte[j] shr(2); //a->A;
inc(jj);
_2byte[jj]:=byte(_1byte[j] shl(6)) shr(2); //a&b->B
end;
2:
begin
_2byte[jj]:=_1byte[j] shr(2); //a->A;
inc(jj);
_2byte[jj]:=byte(_1byte[j] shl(6)) shr(2) + _1byte[j+1] shr(4); //a&b->B
inc(jj);
_2byte[jj]:=byte(_1byte[j+1] shl(4)) shr(2); //b2->C
end;
end;
//按照编码显示!
str:='';
for i:=0 to high(_2byte) do
begin
str:=str+copy(basetable,_2byte[i]+1,1);
end;
Result := str;
end;
procedure TForm1.Button2Click(Sender: TObject);
begin
edit2.Text := strtoBase64(edit1.Text);
end;
var
_1byte,_2byte:array of byte;
strlen,i,j,jj:integer;
const
basetable='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
begin
//str:='xxc';
//str:='abcabc';
strlen:=length(str);
setlength(_1byte,strlen);
if strlen mod 3 >0 then setlength(_2byte,((strlen div 3) * 4 + strlen mod 3)+1)
else setlength(_2byte,(strlen div 3)*4+(strlen mod 3)+0);
for i:=0 to strlen-1 do
begin
_1byte[i]:=ord(str[i+1]);
end;
j:=0;
jj:=0;
for i:=0 to (strlen div 3)-1 do
begin
j:=i*3;
_2byte[jj]:=_1byte[j] shr(2); //a->A;
inc(jj);
_2byte[jj]:=byte(_1byte[j] shl(6)) shr(2) + _1byte[j+1] shr(4); //a&b->B
inc(jj);
_2byte[jj]:=byte(_1byte[j+1] shl(4)) shr(2)+_1byte[j+2]shr(6); //b&c->C
inc(jj);
_2byte[jj]:=byte(_1byte[j+2] shl(2))shr(2);
inc(jj);
end;
j:=(strlen div 3)*3;
case (strlen mod 3) of
1:
begin
_2byte[jj]:=_1byte[j] shr(2); //a->A;
inc(jj);
_2byte[jj]:=byte(_1byte[j] shl(6)) shr(2); //a&b->B
end;
2:
begin
_2byte[jj]:=_1byte[j] shr(2); //a->A;
inc(jj);
_2byte[jj]:=byte(_1byte[j] shl(6)) shr(2) + _1byte[j+1] shr(4); //a&b->B
inc(jj);
_2byte[jj]:=byte(_1byte[j+1] shl(4)) shr(2); //b2->C
end;
end;
//按照编码显示!
str:='';
for i:=0 to high(_2byte) do
begin
str:=str+copy(basetable,_2byte[i]+1,1);
end;
Result := str;
end;
procedure TForm1.Button2Click(Sender: TObject);
begin
edit2.Text := strtoBase64(edit1.Text);
end;