我試圖在 Delphi 中使用來自 Karsten Ohme (kaoh)的GlobalPlatform 庫。感謝stackoverflow上一些人的幫助,我得到了部分作業,我能夠建立與讀卡器的連接。現在我正在嘗試選擇一個 AID,因此我需要將 AID 作為位元組陣列傳遞給函式。
我使用 GPSShell(使用相同庫的命令列工具)源代碼作為參考來幫助我翻譯這些函式。在那里我找到了 convertStringToByteArray 函式,它接受一個字串并將其轉換為一個位元組陣列。
原始 C 函式:
static int convertStringToByteArray(TCHAR *src, int destLength, BYTE *dest)
{
TCHAR *dummy;
unsigned int temp, i = 0;
dummy = malloc(destLength*2*sizeof(TCHAR) sizeof(TCHAR));
_tcsncpy(dummy, src, destLength*2 1);
dummy[destLength*2] = _T('\0');
while (_stscanf(&(dummy[i*2]), _T("x"), &temp) > 0)
{
dest[i] = (BYTE)temp;
i ;
}
free(dummy);
return i;
}
我嘗試在 Delphi 中撰寫類似的程式,我嘗試以兩種方式轉換字串 - 第一種(字面意思)將每個字符(被視為 HEX)轉換為整數。第二種方式使用 Move:
procedure StrToByteArray(Input: AnsiString; var Bytes: array of Byte; Literally: Boolean = false);
var
I, B : Integer;
begin
if Literally then
begin
for I := 0 to Length(Input) -1 do
if TryStrToInt('$' Input[I 1], B) then
Bytes[I] := Byte(B)
else
Bytes[I] := Byte(0);
end else
Move(Input[1], Bytes[0], Length(Input));
end;
但我一直得到一個
(6A82:找不到要選擇的應用程式。)
錯誤,當我嘗試選擇 AID 時
A000000003000000
我知道我正在嘗試選擇正確的 AID,因為當我將相同的 AID 與 GPSShell 一起使用時 - 我得到了成功的回應。所以我不確定問題出在我的字串到位元組陣列程序中,還是在其他地方。
當我使用斷點時,我嘗試將字串從字面上轉換為位元組
(10, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0)
在除錯器中。但是當我嘗試使用 Move(或 ORD)時,我得到了
(65, 48, 48, 48, 48, 48, 48, 48, 48, 51, 48, 48, 48, 48, 48, 48)
我還嘗試通過各種網站在線將字串轉換為位元組,這些給了我另一個結果
(41, 30, 30, 30, 30, 30, 30, 30, 30, 33, 30, 30, 30, 30, 30, 30)
所以我有點迷失在試圖找出我做錯了什么,是我的字串到位元組轉換的問題 - 還是我需要看看其他地方?
uj5u.com熱心網友回復:
原始 C 代碼將成對的十六進制數字決議為位元組:
A000000003000000->A0 00 00 00 03 00 00 00
但是您的 Delphi 代碼將單個十六進制數字決議為位元組:
A000000003000000->A 0 0 0 0 0 0 0 0 3 0 0 0 0 0 0
試試這個:
procedure StrToByteArray(Input: AnsiString; var Bytes: TBytes; Literally: Boolean = false);
var
I, B : Integer;
begin
if Literally then
begin
SetLength(Bytes, Length(Input) div 2);
for I := 0 to Length(Bytes)-1 do
begin
if not TryStrToInt('$' Copy(Input, (I*2) 1, 2), B) then
B := 0;
Bytes[I] := Byte(B);
end;
end else
begin
SetLength(Bytes, Length(Input));
Move(Input[1], Bytes[0], Length(Input));
end:
end;
話雖如此,Delphi 有自己的HexToBin()函式將十六進制字串決議為位元組陣列。您不需要撰寫自己的決議器,例如:
procedure StrToByteArray(Input: AnsiString; var Bytes: TBytes; Literally: Boolean = false);
begin
if Literally then
begin
SetLength(Bytes, Length(Input) div 2);
HexToBin(PAnsiChar(Input), PByte(Bytes), Length(Bytes));
end else
begin
SetLength(Bytes, Length(Input));
Move(Input[1], Bytes[0], Length(Input));
end:
end;
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/460935.html
