首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > .NET > .NET >

delphi中怎的把string转为array of byte

2013-06-25 
delphi中怎样把string转为array of byte?如,我的string为CA 01 A0 A1,我要把其转换为byte数组然后用串口发

delphi中怎样把string转为array of byte?
如,我的string为CA 01 A0 A1,我要把其转换为byte数组然后用串口发出,如何能让设备收到的也是CA 01 A0 A1,而不是一串数字?
[解决办法]
你的string中的字符是表示的16进制的数?那你可以直接StrToInt()

从源字符串中取出2个字符构成一个临时字符串

比如:
s2:='CA';
s2:='$'+s2;
aByte:=inttostr(s2);

哈哈,要说清楚啊

[解决办法]
function TForm1.HexStrToByte(HesStr: String): Byte;
var
  iLen: Integer;
begin
  Result := 0;
  iLen := length(HesStr);
  if iLen <> 2 then Exit;
  If not (HesStr[1] in ['0'..'9', 'A', 'B', 'C', 'D', 'E', 'F',
   'a', 'b', 'c', 'd', 'e', 'f']) Then Exit;
  If not (HesStr[2] in ['0'..'9', 'A', 'B', 'C', 'D', 'E', 'F',
   'a', 'b', 'c', 'd', 'e', 'f']) Then Exit;
   Result := StrToInt('$' + HesStr);
end;
procedure TForm1.Button1Click(Sender: TObject);
const
  SHEX = 'CA01A0A1';
var
  iByte: Byte;
  sTemp: String;
  hexBuf: array[0..1023] of byte;
  iStart, iCount, idex: Integer;
begin
  idex := 0;
  iStart := 1;
  fillchar(hexBuf, sizeOf(hexBuf), #0);
  iCount := length(SHEX) + 1;
  while iStart < iCount do
  begin
    sTemp := SHEX[iStart];
    iStart := iStart + 1;
    if iStart >= iCount then Break;
    sTemp := sTemp + SHEX[iStart];
    iByte := HexStrToByte(sTemp);
    ShowMessage(IntToHex(iByte, 2));
    hexBuf[idex] := iByte;
    idex := idex + 1;
    iStart := iStart + 1;
  end;
end;
就是上面的代码了! 你测试一下看看是不是你要的!  

热点排行