【问题标题】:How to convert AnsiStr to Bytes and vice versa?如何将 AnsiStr 转换为字节,反之亦然?
【发布时间】:2021-08-13 20:48:53
【问题描述】:

希望有人可以帮助我解决这个问题 - 我必须从这样指定的接口读取数据:

使用 TDataPortTCP,我可以使用 Dataport.Peek(size) 读取缓冲区并使用 Dataport.Pull(size) 从缓冲区中提取数据 - 这两种方法都将结果作为 AnsiStr 提供

我想这样的事情应该可以工作,但我不知道如何将 AnsiStr 转换为 Bytes,反之亦然:

   while DataPortTCP.Peek(2) > ZeroBytes do
   begin
      LengthInBytes := DataPortTCP.Pull(2) ;
      sContent := DataPortTCP.Pull(LengthInByte) ;
   end;

如何声明/获取/转换 ZeroBytes 和 LengthInBytes 以及如何处理 Endianess ?

不幸的是,我对 TBytes 一无所知,到目前为止我所读到的内容只会导致更多的混乱 ;-)

如果有人能指出我正确的方向,我将不胜感激。

【问题讨论】:

  • 你需要知道文本编码是什么
  • 接收到的数据是标准ASCII,DataPortTCP以ANSI字符串的形式提供数据

标签: string byte pascal lazarus


【解决方案1】:

判断一个字符串是否不为空,可以对比''

要从字符串中检索字节值,您可以访问该字符并应用ord 函数。

网络顺序是大端,表示第一个字节的顺序更高。因此,您需要使用shl 将其向左移动。在这种情况下,有两个字节,所以第一个 on 移动了 8 位,相当于将它乘以 256。

var
  LengthInBytesStr: String;
  LengthInBytes: Word;

begin
  ...
  while DataPortTCP.Peek(2) <> '' do
  begin
    LengthInBytesStr := DataPortTCP.Pull(2);
    LengthInBytes := (ord(LengthInBytesStr[1]) shl 8)
                   + ord(LengthInBytesStr[2]);

    sContent := DataPortTCP.Pull(LengthInByte);
  end;
  

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-04
    • 2014-11-30
    • 1970-01-01
    相关资源
    最近更新 更多