Discuz! BBS

 找回密码
 立即注册
搜索
热搜: 活动 交友 discuz
查看: 583|回复: 1

Delphi 将整数转为4字节, 将字串和字节互转

[复制链接]

254

主题

363

帖子

2431

积分

管理员

Rank: 9Rank: 9Rank: 9

积分
2431
发表于 2024-12-6 23:35:24 | 显示全部楼层 |阅读模式
一> 将一个长整型,转换成字节:
  1. function TForm1.longToBytes(value: Longint): TBytes;
  2. begin
  3.     SetLength(result, sizeOf(value));
  4.     move(value, result[0], sizeOf(value));
  5. end;
复制代码
因为长整型有4个字节,所以转出来的字串也有相同的长度。

二> 将字符串转换成字节:
  1. function TForm1.stringToBytes(const str : string): TBytes;
  2.     var i: integer;
  3. begin
  4.     setLength(result, length(str));
  5.     for i := 0 to length(str)-1 do
  6.         result[i] := Ord(str[i+1]);  // Note:  Ord(str[i  +1  ] !  将一个char转换成ascii码
  7.     end;
复制代码


三>  将字节转换成字符串:
  1. function TForm1.bytesToString(const bytes : TBytes): string;
  2.     var
  3.     i: Integer;
  4.     begin
  5.     setLength(result, length(bytes));
  6.     for i := 0 to length(bytes) - 1 do
  7.         result[i+1] := char(bytes[i]);
  8.     end;
复制代码
以上在Delphi2007中测试通过。

回复

使用道具 举报

254

主题

363

帖子

2431

积分

管理员

Rank: 9Rank: 9Rank: 9

积分
2431
 楼主| 发表于 2024-12-13 04:36:51 | 显示全部楼层
使用IdGlobal库的例子:
  1. uses
  2.   IdGlobal; // 确保引入IdGlobal单元

  3. var
  4.   IntegerValue: Integer;
  5.   Bytes: TIdBytes;
  6. begin
  7.   // 假设我们要转换的整数是16909060
  8.   IntegerValue := 16909060;

  9.   // 将整数转换为4个字节
  10.   Bytes := ToBytes(IntegerValue, sizeof(IntegerValue));

  11.   // 此时Bytes数组包含了整数的4个字节表示
  12. end;
复制代码
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

Archiver|手机版|小黑屋|DiscuzX

GMT+8, 2025-4-16 04:59 , Processed in 0.017889 second(s), 18 queries .

Powered by Discuz! X3.4

Copyright © 2001-2020, Tencent Cloud.

快速回复 返回顶部 返回列表