1

16 進数の値を 10 進数の整数に変換する必要があります。これができるユニットはありますか?

ウェブ上でそれについて何かを見つけましたが、あまり役に立ちません。inline asmを使用すると、32 ビット 4 個のパックド配列として表現できることがわかりましたInteger。int32 または int64 を int128 に、またはその逆に変換することがわかりましたが、たとえば 2 つの int64 を使用してint128 を実行するものは何も見つかりませんでしdivた。mulsum

そこで、誰かがこの問題を解決するのを手伝ってくれるかどうか尋ねます。私の目的は、文字列を 16 進数で取得して 10 進数に変換し、その後base 35(0..9, A..Z) で同等の値を計算することです。どうもありがとう。

4

1 に答える 1

5

16 進文字列をバイト配列に変換する場合 (SysUtils を参照)、次のコードを使用して base 35 に変換できます。

function EncodeBaseX( const Values: array of Byte; var Dest: array of Byte; Radix: Integer ): Boolean;
var
  i,j,Carry: Integer;
begin
  // We're unsuccesful up to now
  Result := False;

  // Check if we have an output buffer and clear it
  if Length( Dest ) = 0 then Exit;
  System.FillChar( Dest[ 0 ], Length( Dest ), 0 );

  // fill in the details
  for i := 0 to High( Values ) do begin
    Carry := Values[ i ];
    for j := 0 to High( Dest ) do begin
      Inc( Carry, Radix * Dest[ j ] );
      Dest[ j ] := Carry and $ff;
      Carry := Carry shr 8;
    end;
    if Carry <> 0 then Exit; // overflow
  end;

  // We're succesful
  Result := True;
end;

{Bytes: array of byte (0..255); Dest: array of Byte(0..Radix-1)}
function DecodeBaseX( const Bytes: array of Byte; var Dest: array of Byte; Radix: Integer ): Boolean;
var
  i,j,Carry: Integer;
  B: array of Byte;
begin
  // We're unsuccesful up to now
  Result := False;

  // Copy data
  if Length( Bytes ) = 0 then Exit;
  SetLength( B, Length( Bytes ) );
  System.Move( Bytes[ 0 ], B[ 0 ], Length( B ) );

  // fill in the details
  for i := High( Dest ) downto 0 do begin
    Carry := 0;
    for j := High( Bytes ) downto 0 do begin
      Carry := Carry shl 8 + B[ j ];
      B[ j ] := Carry div Radix; Carry := Carry mod Radix;
    end;
    Dest[ i ] := Carry;
  end;

  // Check if we collected all the bits
  Carry := 0;
  for i := 0 to High( B ) do Carry := Carry or B[ i ];

  // We're succesful if no bits stayed pending.
  Result := ( Carry = 0 );
end;

次に、base 35 バイトを文字に変換します。

function EncodeKeyToString( const Num128Bits: array of Byte ): Ansistring;
var
  Src:   array [0..15] of Byte; // your 128 bits
  Dest:  array [0..24] of Byte;
  i:     Integer;
const
  EncodeTable: AnsiString = '0123456789ABCDEFGHIJKLMNPQRSTUVWXYZ'; 
  // O is not present to make base 35. If you want a different code, be my guest.
begin
  // Convert to an array of 25 values between 0-35
  System.Move( Num128Bits[ 0 ], Src[ 0 ], Length( Src ) ); // Copy data in our private placeholder
  DecodeBaseX( Src, Dest, 35 );    

  // Convert to a representable string
  SetLength( Result, Length( Dest ) );
  for i := 0 to High( Dest ) do begin
    Assert( Dest[ i ] < Length( EncodeTable ) );
    Result[ i + 1 ] := EncodeTable[ 1 + Dest[ i ] ];
  end;
end;

128ビットの数学は必要ないと思います..

幸運を!

于 2011-09-10T20:50:15.060 に答える