delphibase64decode

Base64 Decoding Error :No mapping for the Unicode character exists in the target multi-byte code page


I’m working on a Delphi project where I need to decode a base64 string extracted from a QR code. The QR code contains a mix of textual data, dates, numeric values. Here’s an example of the base64 string I’m working with:

AT9NVU5JUiBBQkRVTExBSCBBTE1VTklGIEZBQ1RPUlkgRk9SIFBMQVNUSUMgUElQRVMgJiBGSVRUSU5HUyBDTy4CDzMwMDUyODA3OTYwMDAwMwMTMjAyNC0xMC0xM1QwNDo0MDoyMwQINDM5NTIuNDEFBzU3MzIuOTIGLFdPMkt1TE9CS2tkMkdRSnU1ZTA3Zzd3RU5vVXFoVy92UFZVTzA5UkdWTzQ9B2BNRVFDSUVPYm95MjRmNExMYzRFeDlEdkpqbUxnYU5BWS9Ybmo2UGhlUWNxYVYwbUxBaUJjVDZlZ2VpKzBXMFhNbVc1bW9FOWh5QUFwdjJCRUtXS2t6dWJ5UENKSGdnPT0IWDBWMBAGByqGSM49AgEGBSuBBAAKA0IABKjKpalSynCgT1a7cnHqONrPEWyCpcqx2PLnhzmXsH1CtjSbfljxm5adWyeZ2ekTcynTBhMXAkmW85x+SGllB5w=

When I try to decode this using TNetEncoding.Base64.Decode in Delphi, I get the following error:

No mapping for the Unicode character exists in the target multi-byte code page.

I have noted that the error never happened if the QR string is shorter than the above example. also I have tried the next and still get the same error :

DecodedBytes := TNetEncoding.Base64.DecodeStringToBytes(QRstr);
DecodeString := TEncoding.UTF8.GetString(DecodedBytes);

Any advice or example code would be greatly appreciated!


Solution

  • The QR code encoded data in your example contains binary information that cannot be converted to Unicode string.

    Your code doesn't fail on Base64 decoding, but on converting bytes to string in following line:

    DecodeString := TEncoding.UTF8.GetString(DecodedBytes);
    

    You will have to work with DecodedBytes and parse it according to its binary format specification.