Supply
Supply

Reputation: 51

Delphi 10.1 No mapping for unicode character exists in target multi-byte code page

I'm trying to decode base64 string

Sample:='MEIEEPgAAAAAAAAAAAAAAAAAAAEwFAYIKoZIhvcNAwcECO9X2Lfq3EYMBBiX0/4McWT3y6hWMvOJvH5MwD22EOvPbLQ=';
Result:=DecodeString(Sample);

Got an error: "No mapping for unicode character exists in target multi-byte code page". What am i doing wrong?

Upvotes: 1

Views: 6464

Answers (1)

David Heffernan
David Heffernan

Reputation: 613063

Your code sample is incomplete, but I can only assume that DecodeString is the function from Soap.EncdDecd. Given that assumption, the call to DecodeString does indeed raise the exception that you describe.

The exception is caused by a very common misconception, namely that binary and text data are interchangeable. When you call DecodeString you are actually asking for two operations to take place:

  1. Decode the base64 data to binary, i.e. an array of bytes.
  2. Interpret this binary data as UTF-8 encoded text, and decode to a native Delphi string.

The first of these operations succeeds because the base64 data is valid. The second operation fails because the binary data is not valid UTF-8 encoded text.

Most likely you are making the erroneous, albeit very common, mistake of wanting to treat binary data, an array of bytes, as a string. A string is not the same thing as an array of bytes.

You have binary data, so treat it as such:

uses
  System.NetEncoding;

var
  base64: string;
  bytes: TBytes;
....
base64 := 'MEIEEPgAAAAAAAAAAAAAAAAAAAEwFAYIKoZIhvcNAwcECO9X2Lfq3EYMBBiX0/4McWT3y6hWMvOJvH5MwD22EOvPbLQ=';
bytes := TNetEncoding.Base64.DecodeStringToBytes(base64);

Upvotes: 3

Related Questions