Welcome

首页 / 软件开发 / 数据结构与算法 / 算法:62进制的简单实现

算法:62进制的简单实现2013-11-14 博客园 万一62 进制需要的字符及次序: 0..9 a..z A..Z; 只实现了 62 进制字符串与正整数的互换.

unit H62; interfaceuses SysUtils; function IntToH62(N: UInt64): string; //整数转到 62 进制字符串function H62ToInt(S: string): UInt64; //62 进制字符串转到整数implementationfunction _C2B(C: Char): Byte; inline;beginResult := 0;if CharInSet(C, ["0".."9"]) then Exit(Byte(C) - 48);//0..9if CharInSet(C, ["a".."z"]) then Exit(Byte(C) - 97 + 10); //a..zif CharInSet(C, ["A".."Z"]) then Exit(Byte(C) - 65 + 36); //A..Zend; function _B2C(B: Byte): Char; inline;beginResult := #0;if B <= 9then Exit(Char(B + 48)); //0..9if (B >= 10) and (B <= 35) then Exit(Char(B - 10 + 97)); //a..zif (B >= 36) and (B <= 61) then Exit(Char(B - 36 + 65)); //A..Zend; function _Power(B,P: Cardinal): UInt64; inline;vari: Integer;beginResult := B;for i := 1to P-1do Result := Result * B;end; function _C2V(C: Char; N: Byte): UInt64; inline;beginResult := 0;if (N = 0) then Exit(_C2B(C));if (N > 0) then Result := _C2B(C) * _Power(62, N);end; function IntToH62(N: UInt64): string;varC: Char;beginResult := "";repeatC := _B2C(N mod62);Result := C + Result;N := N div62;until (N = 0);end; function H62ToInt(S: string): UInt64;varC: Char;L,N,I: Cardinal;beginResult := 0;L := Length(S);if L > 11thenraise Exception.Create("Err: H62ToInt"); //不能多于 11 位for I := L downto1dobeginC := S[I];N := L - I;Result := Result + _C2V(C, N);end;end; end.
//测试:uses H62; procedure TForm1.FormCreate(Sender: TObject);varn: Cardinal;I: UInt64;str: string;beginstr := IntToH62(MaxInt);// 2lkCB1n := H62ToInt(str); // 2147483647 I := 9999999999999999999; // 19 位str := IntToH62(I); // bUI6zOLZTrh str := "ZZZZZZZZZZZ"; // 最大值I := H62ToInt(str); // 15143072536417990655; 比 UInt64 的最大值(18446744073709551615)小一点, 比 Int64 的最大值(9223372036854775807)大一点end;