Registriert seit: 30. Dez 2004
Ort: Ruhrpott
239 Beiträge
Delphi 10.4 Sydney
|
Re: unicodefähiges Base32Decode
3. Feb 2010, 14:13
Hier Code von Embarcadero, der einwandfrei auch unter D2010 funktioniert:
Delphi-Quellcode:
const
ValidChars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567';
function FromBase32String(const inString : string) : string;
var
outString : string;
aByte : byte;
bit_buffer,
inIndex,
bits_in_buffer,
outSize,
pos1, pos2,
i : integer;
begin
outSize := (length(inString) * 5 div 8) + 1;
outString := StringOfChar(' ',outSize);
pos1 := Pos(inString[1],ValidChars) - 1;
pos2 := Pos(inString[2],ValidChars) - 1;
bit_buffer := pos1 or (pos2 shl 5);
if length(inString) < 3 then begin
aByte := bit_buffer;
outString[1] := Chr(aByte);
result := outString;
exit;
end;
bits_in_buffer := 10;
inIndex := 3;
for i := 1 to outSize + 1 do begin
aByte := bit_buffer;
outString[i] := Chr(aByte);
bit_buffer := bit_buffer shr 8;
bits_in_buffer := bits_in_buffer - 8;
while (bits_in_buffer < 8) and (inIndex <= length(inString)) do begin
pos1 := (Pos(inString[inIndex],ValidChars) - 1);
Inc(inIndex);
bit_buffer := bit_buffer or (pos1 shl bits_in_buffer);
bits_in_buffer := bits_in_buffer + 5;
end;
end;
result := outString;
end;
function ToBase32String(const inString : string) : string;
var
currentChar,
outString : string;
inIndex,
validIndex,
high : integer;
aByte,
currentByte : byte;
begin
high := 5;
inIndex := 1;
while inIndex <= Length(inString) do begin
currentChar := inString[inIndex];
currentByte := Ord(currentChar[1]);
if (high > 8) then begin
// get the last piece from the current byte, shift it to the right
// and increment the byte counter
validIndex := (currentByte shr (high - 5)) mod 256;
Inc(inIndex);
currentChar := inString[inIndex];
currentByte := Ord(currentChar[1]);
if (inIndex <> Length(inString) + 1) then begin
// if we are not at the end, get the first piece from
// the next byte, clear it and shift it to the left
aByte := (currentByte shl (16 - high)) mod 256;
validIndex := ((aByte shr 3 ) or validIndex) mod 256;
end;
high := high - 3;
end else if(high = 8) then begin
Inc(inIndex);
validIndex := currentByte shr 3;
high := high - 3;
end else begin
// simply get the stuff from the current byte
aByte := currentByte shl (8 - high) mod 256;
validIndex := aByte shr 3;
high := high + 5;
end;
currentChar := ValidChars[validIndex + 1];
outString := outString + currentChar;
end;
result := outString;
end;
Ein Vergleich mit den beiden Funktionen von dir lässt auf einen Fehler im Encoder schließen, da der Decoder das gleiche Ergebnis erzeugt.
Stefan
|
|
Zitat
|