A simple implementation of a band of 62

Recommended for you: Get network issues from WhatsUp Gold. Not end users.

Character and order 62 hexadecimal need: 0..9 a..Z A..Z; only the exchange of 62 hexadecimal strings and integers.

unit H62;

interface

uses SysUtils;

function IntToH62(N: UInt64): string; //Integer to 62 hexadecimal string
function H62ToInt(S: string): UInt64; //62 hexadecimal string to integer

implementation

function _C2B(C: Char): Byte; inline;
begin
  Result := 0;
  if CharInSet(C, ['0'..'9']) then Exit(Byte(C) - 48);      //0..9
  if CharInSet(C, ['a'..'z']) then Exit(Byte(C) - 97 + 10); //a..z
  if CharInSet(C, ['A'..'Z']) then Exit(Byte(C) - 65 + 36); //A..Z
end;

function _B2C(B: Byte): Char; inline;
begin
  Result := #0;
  if B = 10) and (B = 36) and (B  0) then Result := _C2B(C) * _Power(62, N);
end;

function IntToH62(N: UInt64): string;
var
  C: Char;
begin
  Result := '';
  repeat
    C := _B2C(N mod 62);
    Result := C + Result;
    N := N div 62;
  until (N = 0);
end;

function H62ToInt(S: string): UInt64;
var
  C: Char;
  L,N,I: Cardinal;
begin
  Result := 0;
  L := Length(S);
  if L > 11 then raise Exception.Create('Err: H62ToInt'); //Not more than 11
  for I := L downto 1 do
  begin
    C := S[I];
    N := L - I;
    Result := Result + _C2V(C, N);
  end;
end;

end.
//Test:
uses H62;

procedure TForm1.FormCreate(Sender: TObject);
var
  n: Cardinal;
  I: UInt64;
  str: string;
begin
  str := IntToH62(MaxInt);  // 2lkCB1
  n := H62ToInt(str);       // 2147483647

  I := 9999999999999999999; // 19
  str := IntToH62(I);       // bUI6zOLZTrh

  str := 'ZZZZZZZZZZZ';     // The maximum value
  I := H62ToInt(str);       // 15143072536417990655; The maximum values than UInt64 (18446744073709551615) is smaller than Int64, the maximum value (922337203685477580) a little
end;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download

Posted by Lauren at January 07, 2014 - 6:40 PM