按位比较并将 C 转换为 Delphi

Bitwise Comparison and Converting C to Delphi

我有以下 C 代码:

pIBM [unsigned char *, a function parameter, for input]
pIEEE [unsigned char *, a function parameter, for output] 

char tmp[8];

memcpy(tmp, pIBM, 8);
memset(pIEEE, 0, 8);

if (*tmp && memcmp(tmp+1, pIEEE, 7) == 0)
{
   pIEEE[0] = pIEEE[1] = 0xff;
   pIEEE[2] = ~(*tmp);

   return;
}
  1. if (*tmp && memcmp(tmp+1, pIEEE, 7) == 0) 是如何工作的?
  2. 如何将 C 代码转换为 Delphi,否则为文字 and/or?
if (*tmp && memcmp(tmp+1, pIEEE, 7) == 0)

这里tmp是一个衰减为指针的数组。所以当 tmp[0] 不等于 0 时 *tmp 为真。当数组的最后 7 个元素与 pIEEE 的内容匹配时,memcmp 测试 returns 为真。 pIEEE 被初始化为包含零。我猜你知道 && 是逻辑 AND 运算符。

如果我在 Delphi 中写这篇文章,它将看起来像这样:

type
  TMyData = array [0..7] of Byte;

function Foo(const IBM: TMyData): TMyData;
begin
  FillChar(Result, 8, 0);
  if (IBM[0]<>0) and CompareMem(@IBM[1], @Result[0], 7) then
  begin
    Result[0] := $ff;
    Result[1] := $ff;
    Result[2] := not IBM[0];
  end;
end;
if (*tmp && memcmp(tmp+1, pIEEE, 7) == 0)

相同
if ((0 != tmp[0]) && (memcmp(&tmp[1], &pIEEE[0], 7) == 0))

所以这是两个测试:

  1. tmp[0] 不包含 [=13=]' 吗?
  2. 七个chartmp[1] .. tmp[7]是否等于七个字符pEEE[0] .. pEEE[6]

How to convert the C code to Delphi, literal and/or otherwise?

  1. 阅读C代码
  2. 理解你阅读的内容
  3. 编写对应的Delphi代码

将是如下内容(抱歉,如果我的 Pascal 技能有点生疏) 对于第一季度:

条件 如果 (*tmp && memcmp(tmp+1, pIEEE, 7) == 0) 可以读作

如果 tmp (*tmp == tmp[0]) 的第一个字符指针不为零 (!= '\0'),则比较从第二个字符开始的 tmp 数组与 pIEEE 数组(最多七个字符) , 如果该比较相等,则执行

pIEEE[0] = pIEEE[1] = 0xff;

pIEEE[2] = ~(*tmp);

至于Q2: 可能类似于

pIBM [PChar,一个函数参数,用于输入] pIEEE [PChar,函数参数,用于输出]

var tmp, tmp2 : PChar;

var flag : SizeInt;

StrLCopy(tmp, pIBM, 8);

pIEEE[0] := #0;

pIEEE[1] := #0;

pIEEE[2] := #0;

pIEEE[3] := #0;

pIEEE[4] := #0;

pIEEE[5] := #0;

pIEEE[6] := #0;

pIEEE[7] := #0;

if ^tmp <> #0 then

begin

   Tmp2 := Tmp;

   Inc(Tmp2);

   Flag := StrLComp(Tmp2, pIEEE, 7);

   if Flag = 0 then

   begin

       pIEEE[0] = #ff;

       pIEEE[1] = #ff;

       pIEEE[2] = not tmp[0];

   end

end;

注意:PChar 是等同于 C 中以 Null 结尾的字符串的类型,请参阅单位 Strings.pas(或在 FreePascal 中 http://www.freepascal.org/docs-html/rtl/sysutils/pcharfunctions.html

致 1:

if (*tmp && memcmp(tmp+1, pIEEE, 7) == 0)

等同于(但还不正确 Delphi):

if (tmp^ <> 0) and (memcmp(tmp + 1, pIEEE, 7) = 0) then

当然那是不合适的Delphi(因为在Delphi中不能以同样的方式对待数组和指针,并且memcmp不是核心的一部分Delphi),所以试试这个:

if (tmp[0] <> 0) and CompareMem(@tmp[1], @pIEEE[0], 7) then

致 2:

var
  tmp: array[0..7] of Byte;
begin
  Move(pIBM[0], tmp[0], SizeOf(tmp));
  FillChar(pIEEE, 8, 0);
  if (tmp[0] <> 0) and CompareMem(@tmp[1], @pIEEE[0], 7) then
  begin
    pIEEE[0] := $FF;
    pIEEE[0] := $FF;
    pIEEE[2] := not tmp[0];
    Exit;
  end;
end;

这或多或少是 "literal" 的翻译。我想你可以看到它可以如何改进一点(通过避免 tmp 并直接从 pIBM 读取)。