Decoding Base 64 encoded data
A while ago someone asked me how to go about decoding Base 64 encoded code in a single routine.
Here's what I came up with. It uses the Indy internet component suite to do the grunt work and simply wraps the various Indy calls into a function.
uses Classes, IdCoderMIME ... function Base64Decode(const EncodedText: string): TBytes; var DecodedStm: TBytesStream; Decoder: TIdDecoderMIME; begin Decoder := TIdDecoderMIME.Create(nil); try DecodedStm := TBytesStream.Create; try Decoder.DecodeBegin(DecodedStm); Decoder.Decode(EncodedText); Decoder.DecodeEnd; Result := DecodedStm.Bytes; finally DecodedStm.Free; end; finally Decoder.Free; end; end;
This function decodes the encoded text passed in EncodedText, which must contain only valid Base 64 encoding characters, and returns the resulting raw data as an array of bytes.
We use Indy's TIdDecoderMIME component to decode the text into a TByteStream and read of the result from the stream's Bytes property.
Comments
Post a Comment
Comments are very welcome, but please don't comment here if:
1) You have a query about, or a bug report for, one of my programs or libraries. Most of my posts contain a link to the relevant repository where there will be an issue tracker you can use.
2) You have a query about any 3rd party programs I feature, please address them to the developer(s) - there will be a link in the post.
3) You're one of the tiny, tiny minority who are aggressive or abusive - in the bin you go and reported you will be!
Thanks