读书人

关于文本转换为BYTE数组的有关问题,请

发布时间: 2012-03-20 14:01:10 作者: rapoo

关于文本转换为BYTE数组的问题,请大家帮忙修改代码
利用下面的代码把例如25 00 07 00 00 00 08 80的文本转换为BYTE数组(发包用)时发现最后一位,即80无法正确转换,有时会出现00的情况


//调用
Len := BinaryDecode(Edit1.Text, @byt[0], sizeof(byt))+1;//Edit1.Text里面是如上的文本数据
Memo1.Lines.Add(IntToStr(byt[Len-1]));//用这句话显示换后的数组最后一位,有时会显示成0,说明转换时出了问题,请参考下面的转换代码

//变量声明
Byt:array [0..1000] of Byte;//发包内容

//转换程序
function GetByte(const V: Char): Byte;
begin
case V of
'a '.. 'f ':
Result := Ord(V) - Ord( 'a ') + 10;
'A '.. 'F ':
Result := Ord(V) - Ord( 'A ') + 10;
else
Result := Ord(V) - Ord( '0 ');
end;
end;

function BinaryDecode(const S: string; output: PByte; outlen: Integer): Integer;
var
R: PByte;
P: PChar;
I: Integer;
begin
Result := Length(S) div 3;
if outlen < Result then
raise Exception.Create( 'outlen too small ');

P := PChar(S);
R := output;
for I := 1 to Result do
begin
R^ := GetByte(P[0]) * 16 + GetByte(P[1]);
Inc(R);
Inc(P, 3);
end;
end;


[解决办法]
那是你的
Len := BinaryDecode(Edit1.Text, @byt[0], sizeof(byt))+1 //这里多加了一个1了,去掉

读书人网 >.NET

热点推荐