不就是Base64编码嘛,以前写着玩的,用的时候自己注意释放内存和出错处理
function GetBase64Char(const c: char): char;
begin
if ((c >= 'A') and (c <= 'Z')) then result := char(ord(c) - ord('A'))
else if ((c >= 'a') and (c <= 'z')) then result := char(ord(c) - ord('a') + 26)
else if ((c >= '0') and (c <= '9')) then result := char(ord(c) - ord('0') + 52)
else if (c = '+') then result := char(62)
else if (c = '/') then result := char(63)
else if (c = '=') then result := char(0)
else exit
//错误的字符
end;
function Base64Decode(source: string): pchar;
var psource, ptmp, pdest: pchar;
chunk: array[0..3] of char;
sourcelen, destlen, times, i: integer;
begin
psource := pchar(source);
sourcelen := Length(source);
if sourcelen mod 4 <> 0 then
begin
showmessage(inttostr(sourcelen mod 4));
exit
//错误的字符串长度
end;
times := sourcelen div 4;
destlen := 3 * times;
if (psource[sourcelen - 1] = '=') then dec(destlen);
if (psource[sourcelen - 2] = '=') then dec(destlen);
pdest := allocMem(destlen);
i:=0;
while (times>0) do
begin
chunk[0] := GetBase64Char(psource[0]);
chunk[1] := GetBase64Char(psource[1]);
chunk[2] := GetBase64Char(psource[2]);
chunk[3] := GetBase64Char(psource[3]);
pdest := char(ord(chunk[0]) shl 2 or ord(chunk[1]) shr 4);
if (psource[2] = '=') then break;
pdest[i+1] := char(ord(chunk[1]) shl 4 or ord(chunk[2]) shr 2);
if (psource[3] = '=') then break;
pdest[i+2] := char((ord(chunk[2]) shl 6) or ord(chunk[3]));
inc(psource, 4);
inc(i, 3);
dec(times);
end;
pdest := #0;
result := pdest;
end;