Base24编码以及解码的实现

unit Base24Unt;

{Base24 算法}

interface

uses Windows,Sysutils,Dialogs;

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;
procedure Base24ToByte(sValue:String;var buf:array of byte);
function GetValIndex(tmpchar:String):Integer;


implementation

function GetValIndex(tmpchar:String):Integer;
var
  i:Integer;
begin
  for i:=0 to 24 do
  begin
    if tmpchar=EncodeTable[i] then
    begin
      result:=i;
      break;
    end;
  end;
end;

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 shl 8) + buf[j];
    buf[j] := K div 24;
    K := K mod 24;
    end;
  Result :=ConCat(EncodeTable[K],Result);
  If (i Mod 5 = 0) And (i <> 0) Then
     Result := ConCat('-' , Result);
  end;
end;

procedure Base24ToByte(sValue:String;var buf:array of byte);
var
  i,j,m:Integer;
  K:Longword;
  tmpchar:string;
  TmpBuffer:array[0..24] of Byte;
begin
  sValue:=StringReplace(sValue,'-','',[rfReplaceAll, rfIgnoreCase]);
  k:=0;
  for i:=0 to 24 do
  begin
   tmpchar:=copy(sValue,i+1,1);
   m:=GetValIndex(tmpchar);
   k:=m;
   for j:=0 to 14 do
   begin
     k:=(buf[j]*24+k);
     buf[j]:=K mod 256;
     K:=K div 256;
   end;
  end;
end;


end.

posted @ 2013-01-06 15:50  骑着骆驼逛沙漠  阅读(1700)  评论(0编辑  收藏  举报