我有一個標記的阿拉伯字串,我想使用 Base64 編碼來編碼這個字串。對此字串使用英文字母時,一切運行完美,但使用阿拉伯字母時,QR 閱讀器不會顯示正確的字母。
這是我的代碼:
function TForm1.GetMyString(TagNo: Integer; TagValue: string): string;
var
Bytes, StrByte: TBytes;
i: Integer;
begin
SetLength(StrByte, Length(TagValue) 2);
StrByte[0] := Byte(TagNo);
StrByte[1] := Byte(Length(TagValue));
for i := 2 to Length(StrByte)-1 do
StrByte[i] := Byte(TagValue[i-1]);
Result := TEncoding.UTF8.GetString(StrByte);
end;
procedure TForm1.Button1Click(Sender: TObject);
var
s: String;
Bytes: TBytes;
begin
s := GetMyString(1, Edit1.Text) GetMyString(2, Edit2.Text)
GetMyString(3, Edit3.Text) GetMyString(4, Edit4.Text)
GetMyString(5, Edit5.Text);
bytes := TEncoding.UTF8.GetBytes(s);
QREdit.Text := TNetEncoding.Base64.EncodeBytesToString(Bytes);
end;
在解碼 Base64 字串后,它也顯示相同的 QR 讀取結果,例如。(E$33) 'D9E1'F)代替(????? ???????)
我正在使用 ZXingQR 讀取生成的字串。
uj5u.com熱心網友回復:
GetMyString()正在將一系列 UTF-16 字符截斷為 8 位位元組陣列,并將其他非文本位元組放入陣列中,然后將整個陣列視為 UTF-8(它不是)來產生一個新的 UTF-16 字串。
然后Button1Click()將這些自升式 UTF-16 字串連接在一起,并將結果轉換為 UTF-8 以編碼為 base64。
此方法僅適用于長度小于 128 個字符的 ASCII 字串和值小于 128 的標記,因為 0..127 范圍內的 ASCII 位元組是 UTF-8 的子集。這不適用于此范圍之外的非 ASCII 字符/位元組。
您似乎想要對一系列標記的 UTF-8 字串進行 base64 編碼。如果是這樣,請嘗試更多類似的方法:
procedure TForm1.GetMyString(TagNo: UInt8; const TagValue: string; Output: TStream);
var
Bytes: TBytes;
begin
Bytes := TEncoding.UTF8.GetBytes(TagValue);
Assert(Length(Bytes) < 256);
Output.WriteData(TagNo);
Output.WriteData(UInt8(Length(Bytes)));
Output.WriteData(Bytes, Length(Bytes));
end;
procedure TForm1.Button1Click(Sender: TObject);
var
Stream: TMemoryStream;
begin
Stream := TMemoryStream.Create;
try
GetMyString(1, Edit1.Text, Stream);
GetMyString(2, Edit2.Text, Stream);
GetMyString(3, Edit3.Text, Stream);
GetMyString(4, Edit4.Text, Stream);
GetMyString(5, Edit5.Text, Stream);
QREdit.Text := TNetEncoding.Base64.EncodeBytesToString(Stream.Memory, Stream.Size);
finally
Stream.Free;
end;
end;
或者:
function TForm1.GetMyString(TagNo: UInt8; const TagValue: string): TBytes;
var
Len: Integer;
begin
Len := TEncoding.UTF8.GetByteCount(TagValue);
Assert(Len < 256);
SetLength(Result, 2 Len);
Result[0] := Byte(TagNo);
Result[1] := Byte(Len);
TEncoding.UTF8.GetBytes(TagValue, 1, Length(TagValue), Result, 2);
end;
procedure TForm1.Button1Click(Sender: TObject);
var
Bytes: TBytes;
begin
Bytes := Concat(
GetMyString(1, Edit1.Text),
GetMyString(2, Edit2.Text),
GetMyString(3, Edit3.Text),
GetMyString(4, Edit4.Text),
GetMyString(5, Edit5.Text)
);
QREdit.Text := TNetEncoding.Base64.EncodeBytesToString(Bytes);
end;
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/412472.html
標籤:
