动态字节数组的转换 Tbytes String、ANSIString及TBytes之间的转换

一、string转为ansistring
1、直接赋值 (有警告)
2、ansistring()类型强制转换。(无警告)

二、ansistring 转为string

1、直接赋值 (有警告)
2、string()类型强制转换。(无警告)

三、string 转为Tbytes

1、bytes:= bytesof(str) 已转为ansi编码
2、bytes:= widebytesof(str) UNICODE 编码

四、ansistring 转为Tbytes

1、bytes:= bytesof(str) ansi编码
2、bytes:= widebytesof(string(str)) UNICODE 编码

五、Tbytes 转为string

1、 str:=stringof(bytes) Tbytes 为ansi编码
2、 str:=widestringof(bytes) Tbytes 为unicode编码

六、PChar转String

用StrPas函数,StrPas(PChar):AnsiString;


{转换 TBytes 到 Integer}
procedure TForm1.Button1Click(Sender: TObject);
var
  bs: TBytes; {TBytes 就是 Byte 的动态数组}
  i: Integer;
begin
  {它应该和 Integer 一样大小才适合转换}
  SetLength(bs, 4);
  bs[0] := $10;
  bs[1] := $27;
  bs[2] := 0;
  bs[3] := 0;

  {因为 TBytes 是动态数组, 所以它的变量 bs 是个指针; 所以先转换到 PInteger}   i := PInteger(bs)^;   ShowMessage(IntToStr(i)); {10000}
end;

{从 Bytes 静态数组到 Integer 的转换会方便些}
procedure TForm1.Button2Click(Sender: TObject);
var
  bs: array[0..3] of Byte;
  i: Integer;
begin
  bs[0] := $10;
  bs[1] := $27;
  bs[2] := 0;
  bs[3] := 0;

  i := Integer(bs);
  ShowMessage(IntToStr(i)); {10000}
end;

{转换到自定义的结构}
procedure TForm1.Button3Click(Sender: TObject);
type
  TData = packed record
    a: Integer;
    b: Word;
  end;
var
  bs: array[0..5] of Byte; {这个数组应该和结构大小一直}
  data: TData;
begin
  FillChar(bs, Length(bs), 0);
  bs[0] := $10;
  bs[1] := $27;

  data := TData(bs);
  ShowMessage(IntToStr(data.a)); {10000}
end;

{转换给自定义结构的一个成员}
procedure TForm1.Button4Click(Sender: TObject);
type
  TData = packed record
    a: Integer;
    b: Word;
  end;
var
  bs: array[0..3] of Byte;
  data: TData;
begin
  FillChar(bs, Length(bs), 0);
  bs[0] := $10;
  bs[1] := $27;

  data.a := Integer(bs);
  ShowMessage(IntToStr(data.a)); {10000}
end;

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值