1.英文編碼
function Encode7bit(Src:String):String;
var Dst:String;
i:Integer;
CurS,NextS:Byte;
TStr:String;
begin
for i:=1 to Length(Src) do begin
//當前是字元按8位分組的第8位,無需編碼(8個字元已縮短為7個)
if (i mod 8)=0 then Continue;
//取當前位為數字
TStr:=Copy(Src,i,1);
CurS:=Ord(TStr[1]);
//當前右移位組中的第一個字元不移位
if (i mod 8)>1 then
CurS:=(CurS shr ((i mod 8)-1) );
//取後一位為數字如果到了字元的結束,不取
if i<Length(Src) then begin
TStr:=Copy(Src,i+1,1);
NextS:=Ord(TStr[1]);
end else
NextS:=0;
//後一位移位 左移
NextS:=(NextS shl (8-(i mod 8)));
//當前移位後加後一位移位後 轉換成為十六進位
Dst:=Dst+IntToHex(CurS+NextS,2);
end;
Result:=Dst;
end;
2、英文解碼
function Decode7bit(Src:String):String;
var Dst:String;
i:Integer;
CurS,ProiS:Byte;
begin
for i:=1 to (Length(Src) div 2) do begin
//將當前位的十六進位轉換為十進位
CurS:=StrToInt('$'+Copy(Src,(i-1)*2+1,2)); //32->50
//取前一位十六進位轉換為十進位
if (i mod 7)<>1 then
ProiS:=StrToInt('$'+Copy(Src,(i-2)*2+1,2)) //C8->200
else
ProiS:=0;
//前一位右移,即將當前字元前移的位取出來
if (i mod 7)>0 then
ProiS:=(ProiS shr (9-(i mod 7)))
else
ProiS:=(ProiS shr 2);
//當前位左移除掉高位
if (i mod 7)>0 then
CurS:=(CurS shl (i mod 7) )
else
CurS:=(CurS shl 7 );
//將第八位設定為0
CurS:=(CurS shr 1);
Dst:=Dst+Chr(CurS+ProiS);
//第七個十六進位內已包含有一個完整的字元
if (i mod 7)=0 then begin
CurS:=StrToInt('$'+Copy(Src,(i-1)*2+1,2)); //32->50
CurS:=(CurS shr 1);
Dst:=Dst+Chr(CurS);
end;
end;//en for
Result:=Dst;
end;
3.中文編碼
function CnToUSC(var s:WideString):String;
var
i,len:Integer;
cur:Integer;
t:String;
begin
Result:= '';
len:=Length(s);
i:=1;
while i<=len do
begin
cur:=ord(s[i]);
//BCD轉換
FmtStr(t,'%4.4X',[cur]);
Result:=Result+t;
inc(i);
end;
end;
4、PDU解碼
function TForm1.DecodeChinese(SRC: String): string; //中文解碼
var
i:Integer;
S:String;
D:WideChar;
ResultW:WideString;
begin
for i:=1 to Round(Length(Src)/4) do
begin
S:=Copy(Src,(i-1)*4+1,4);
D:=WideChar(StrToInt('$'+s)); //此處是重點,用delphi提供的widechar可以轉換
ResultW:=ResultW+D;
end;
Result:=ResultW;
end;