Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Need help implementing Base64Encode/DecodeBytes
#1
Hello,

Can someone help me implement these functions (in Delphi XE4)


function Base64EncodeBytes(Input: TBytes): TBytes;
function Base64DecodeBytes(Input: TBytes): TBytes;

Could be using Indy or Soap.EncdDecd.

Thank you
Rael
Reply
#2
Indy has base64 encoder/decoder classes, TIdEncoderMIME and TIdDecoderMIME, for example:

Code:
uses
 Classes, SysUtils, IdGlobal, IdCoderMIME;

type
  TBytesStreamAccess = class(TBytesStream)
  end;

function Base64EncodeBytes(Input: TBytes): TBytes;
type
  PIdBytes = ^TIdBytes;
var
 Strm: TBytesStream;
begin
 Strm := TBytesStream.Create(nil);
 try
   TIdEncoderMIME.EncodeBytes(PIdBytes(@Input)^, Strm);
    if TBytesStreamAccess(Strm).Capacity > Strm.Size then
      Result := Copy(Strm.Bytes, 0, Strm.Size)
    else
      Result := Strm.Bytes;
 finally
   Strm.Free;
 end;
end;

{ alternatively:
function Base64EncodeBytes(Input: TBytes): TBytes;
type
  PIdBytes = ^TIdBytes;
  PBytes = ^TBytes;
var
 S: String;
 Bytes: TIdBytes;
begin
 S := TIdEncoderMIME.EncodeBytes(PIdBytes(@Input)^);
 Bytes := IndyTextEncoding_ASCII.GetBytes(S);
 Result := PBytes(@Bytes)^;
end;
}

function Base64DecodeBytes(Input: TBytes): TBytes;
var
 InStrm, OutStrm: TBytesStream;
 Decoder: TIdDecoderMIME;
begin
 OutStrm := TBytesStream.Create(nil);
 try
   Decoder := TIdDecoderMIME.Create;
   try
     Decoder.DecodeBegin(OutStrm);
     try
       InStrm := TBytesStream.Create(Input);
       try
         Decoder.Decode(InStrm);
       finally
         InStrm.Free;
       end;
     finally
       Decoder.DecodeEnd;
     end;
   finally
     Decoder.Free;
   end;
    if TBytesStreamAccess(OutStrm).Capacity > OutStrm.Size then
      Result := Copy(OutStrm.Bytes, 0, OutStrm.Size)
    else
      Result := OutStrm.Bytes;
 finally
   OutStrm.Free;
 end;
end;

{ alternatively:
function Base64DecodeBytes(Input: TBytes): TBytes;
type
 PIdBytes = ^TIdBytes;
 PBytes = ^TBytes;
var
 S: String;
 Bytes: PIdBytes;
begin
 S := IndyTextEncoding_ASCII.GetString(PIdBytes(@Input)^);
 Bytes := TIdDecoderMIME.DecodeBytes(S);
 Result := PBytes(@Bytes)^;
end;
}

Reply
#3
Thanks!
Reply


Forum Jump:


Users browsing this thread: 2 Guest(s)