Einzelnen Beitrag anzeigen

gammatester

Registriert seit: 6. Dez 2005
999 Beiträge
 
#20

AW: HexToDec optimieren

  Alt 23. Jun 2014, 10:45
Hier eine alte Routine für wirklich lange Umwandlungen von Bytearrays in Radix-B-Zahlen, schnell aufgebohrt für die Situation hier. Ist etwas allgemeiner da auch andere Ziel-Basen neben 10 nöglich sind.
Delphi-Quellcode:
function base256_to_baseB(var a: array of byte; n: integer; B: byte): string;
  {-n byte of big-endian base 256 number to base B string, a is destroyed}
const
  cmap: array[0..61] of char = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
var
  i,k,m: integer;
  w: word;
  d: byte;
  s: string;
begin
  s := '';
  {k is index of MSB of a}
  k := low(a);
  m := low(a)+n-1;
  repeat
    {One repeat iteration calculates a := a div B;  d := a mod B}
    {initialize "carry"}
    w := 0;
    for i:=k to m do begin
      {loop invariant: 0 <= w < B}
      w := (w shl 8) or a[i];
      if w>=B then begin
        d := w div B;
        w := w mod B;
      end
      else d:=0;
      a[i] := d;
    end;
    {set d to remainder, w is still < B!}
    d := byte(w);
    {add base R digit to result if d is not out of range}
    if d<sizeof(cmap) then s := cmap[d]+s
    else s := '?'+s;
    {if MSB(a) is zero increment lower bound}
    if a[k]=0 then inc(k);
  until k>m;
  base256_to_baseB := s;
end;
Habe mir nicht die Mühe gemacht, die Routine so zu ändern, daß die Eingabe nicht überschrieben wird. Ein Testprogamm für die Funktion
Delphi-Quellcode:
const
  Test: array[0..24] of byte = (
          $9F,$4F,$27,$26,$17,$9A,$22,$45,$01,$D7,$62,$42,$2C,
          $94,$65,$90,$D9,$10,$00,$00,$00,$00,$00,$00,$2A);
var
  s: string;
  tmp: array[0..100] of byte;
  i: integer;
begin
  {Copy because arg is destroyed}
  for i:=0 to sizeof(Test)-1 do tmp[i] := Test[i];
  s := base256_to_baseB(tmp, sizeof(Test), 10);
  writeln('Decimal number: ', s);
end.
liefert dann Decimal number: 10000000000000000000000000000000000000000000000000 00000000042
  Mit Zitat antworten Zitat