delphi提供HexToBin()函數(shù),實際并不好用,因此需要自己編寫一個函數(shù)HenToint(),將2位的十六進制字符串轉換為整數(shù)值。
函數(shù)hex()是將0--f字符轉換為0--15的整數(shù)。
function hex(c:char):Integer ; //將16進制數(shù)轉換為10進制
var
x:integer;
begin
if c=' ' then
x:=0
else if (Ord(c)>=ord('0')) and (Ord(c)<=ord('9')) then
x:=Ord(c)-Ord('0')
else if (Ord(c)>=ord('a')) and (Ord(c)<=ord('f')) then
x:=Ord(c)-Ord('a')+10
else if (Ord(c)>=ord('A')) and (Ord(c)<=ord('F')) then
x:=Ord(c)-Ord('A')+10
else
//輸入錯誤
x:=-1;
Result:=x;
end;
字符類型(Char)
字符類型對應一個英文字符、數(shù)字、符號等字符,在Pascal中為其分配1個字節(jié)的空間,每一字符對應一個編號,我們稱之為ASCII碼(美國國家標準信息交換碼),我們可以用函數(shù)Ord( )來求出某個字符的ASCII碼,如:
Ord(’A’)=65,Ord(’B’)=66,……,Ord(’Z’)=90。
Ord(’a’)=97,Ord(’b’)=98,……,Ord(’z’)=122
Ord(’0’)=48,Ord(’1’)=49,……,Ord(’9’)=57
我們也可以用函數(shù)Chr( )來求出某個ASCII碼對應的字符,如:
Chr(65)= ’ A’,Chr(66)= ’B’……,
由此可以看出:Chr與Ord是兩個互逆運算:如:
Chr(Ord(’1’))= ’1’ ord(chr(99))=99
若要將小寫字母’y’轉換成大寫字母,我們可以Chr(ord(’y’)+32)實現(xiàn);也可以用函數(shù)Upcase( )來實現(xiàn):Upcase(’y’)=’Y’。
//該函數(shù)接收1個至2個字符
//轉換成功.輸出對應16進制數(shù)的值
//轉換失敗.輸出-1。
function HexToInt(S:String): Integer;
var
tmpInt1,tmpInt2:Integer ;
begin
if Length(S)=1 then
begin
Result:=hex(S[1]);
end
else if Length(S)=2 then
begin
tmpInt1:=hex(S[1]);
tmpInt2:=hex(S[2]);
if (tmpInt1=-1) or (tmpInt2=-1) then
Result:=-1
else
Result:= tmpInt1*16+tmpInt2;
end
else
//輸入錯誤,轉換失敗
Result:=-1;
end;
IntToHex
IntToHex(int Value, int Digits) 來源: 在Delphi、Pascal或C++ Builder中使用。 功能: 把一個整型數(shù)字轉換成16進制形式的字符串。 參數(shù)說明: Value 是被轉換的整數(shù),, Digits 是指16進制字符串的位數(shù)。 示例: inttohex(30,1) 返回 1E inttohex(30,4)返回 001E //占的位數(shù)是4 inttohex(30,-3) 返回 1E
本站僅提供存儲服務,所有內容均由用戶發(fā)布,如發(fā)現(xiàn)有害或侵權內容,請
點擊舉報。