delphi Base24编码解码

2018-10-31

unit Base24Unt;

{Base24}

interface

const
  EncodeTable: array[0..23] of Char ='BCDFGHJKMPQRTVWXY2346789' ;

  DecodeTable: array[#0..#127] of Byte = (
    25,25,25,25,25,25,25,25,
    25,25,25,25,25,25,25,25,
    25,25,25,25,25,25,25,25,
    25,25,25,25,25,25,25,25,
    25,25,25,25,25,25,25,25,
    25,25,25,25,25,25,25,25,
    25,25,17,18,19,25,20,21,
    22,23,25,25,25,25,25,25,
    25,25, 0, 1, 2,25, 3, 4,
     5,25, 6, 7,25, 8,25,25,
     9,10,11,25,12,25,13,14,
    15,16,25,25,25,25,25,25,
    25,25,25,25,25,25,25,25,
    25,25,25,25,25,25,25,25,
    25,25,25,25,25,25,25,25,
    25,25,25,25,25,25,25,25);

function ByteToBase24(buf:array of byte):String;
function FormatBase24(sValue:String;Const bAdd:Boolean=False):String;
procedure Base24ToByte(sValue:String;var buf:array of byte);


implementation

function ByteToBase24(buf:array of byte):String;
var
  i,j:Integer;
  K:Longword;
begin
  for i := 24 downto 0 do
    begin
    K := 0;
    for j := High(buf) downto Low(buf) do
      begin
      K := (K * 256) + buf[j];
      buf[j] := K div 24;
      K := K mod 24;
      end;
    Result :=ConCat(EncodeTable[K],Result);
    end;
end;

procedure Base24ToByte(sValue:String;var buf:array of byte);
var
  i,j:Integer;
  K:Longword;
begin
  for i:=0 to 24 do
    begin
    k:=DecodeTable[sValue[i+1]];
    for j:=0 to 14 do
      begin
      K:=buf[j]*24+K;
      buf[j]:=K mod 256;
      k:=K div 256;
      end;
    end;
end;

function FormatBase24(sValue:String;Const bAdd:Boolean=False):String;
var
  i,n:Integer;
begin
Result:='';
n:=Length(sValue);
for i:=1 to n do
  begin
  if bAdd then
    begin
    if (i mod 5=0)and(i<>n) then
      begin
      Result:=ConCat(Result,sValue[i],'-');
      continue;
      end;
    end else begin
    if sValue[i]='-' then continue;
    end;
  Result:=ConCat(Result,sValue[i]);
  end;

end;

end.

阅读69