【问题标题】:Delphi ELF-32 hash algorithm conversion to C#Delphi ELF-32 哈希算法转换为 C#
【发布时间】:2018-06-26 18:18:14
【问题描述】:

我有一个 Delphi 函数可以转换成 C#。我找到了 C# ELF-32 示例,它似乎在 Delphi 中工作,但我对返回的类型有疑问...

这是 Delphi 函数/过程(结果在摘要中,Buf 是要散列的字符串...):

Type
 TByteArray = array[0..32767] of Byte;

procedure HashELF(var Digest : LongInt; const Buf;  BufSize : LongInt);
var
  I, X  : LongInt;
begin
  Digest := 0;
  for I := 0 to BufSize - 1 do begin
    Digest := (Digest shl 4) + TByteArray(Buf)[I];                   {!!.01}
    X := Digest and $F0000000;
    if (X <> 0) then
      Digest := Digest xor (X shr 24);
    Digest := Digest and (not X);
  end;
end;

procedure StringHashELF(var Digest : LongInt; const Str : string);
begin
  HashELF(Digest, Str[1], Length(Str));
end;

function MyHashELF(buffer : string): LongInt;
var
    ELFDigest : LongInt;
begin
     StringHashELF(ELFDigest, buffer);
     result := ELFDigest;
end;

“返回值”是 LONGINT 类型(–2147483648 到 2147483647)

我在网上找到了一些 C# 中的等价物

private static UInt32 MyHashELF(string buffer)
{
    UInt32 hash = 0;
    for (int i = 0; i < buffer.Length; i++)
    {
        hash = (hash << 4) + (byte)buffer[i];
        UInt32 work = (hash & 0xf0000000);
        if (work != 0)
            hash ^= (work >> 24);
        hash &= ~work;
    }
    return hash;
}

但返回类型是 Uint32(0 到 4294967295),如果我想在 Int32 中更改 Uint32,我会遇到以下错误(在 0xf0000000 上):

常量值“4026531840”不能转换为“int”(使用 'unchecked' 语法覆盖)

我已经进行了一些测试,目前它一直与 Delphi 一样工作,但我认为由于类型差异可能存在潜在错误(不是?)。我需要做什么才能 100% 兼容 Delphi 代码?

附:我需要使用原样返回的这 4 个字节作为字符串(一种键)的一部分进行进一步处理...

谢谢

【问题讨论】:

    标签: c# delphi hash


    【解决方案1】:

    4 字节的结果将是相同的。 Delphi longint 和 C# UInt32 之间的区别在于它如何解释这 4 个字节:就好像它是有符号 (longint) 或无符号 (UInt32) 整数值一样。

    因此,如果您真的只需要逐字记录变量底层的这 4 个字节,您可以使用现在的 C# 代码。

    如果您将这 4 个字节存储在它们的 numerical 表示中,那么您将不得不稍微更改 C# 实现,以使其与 Delphi 返回的数值兼容功能。 C# 编译器更喜欢以十六进制表示的常量的无符号值,因此您需要告诉它应该将其视为有符号。只需按照编译器的建议进行操作(添加未选中以覆盖)。将行更改为:

    Int32 work = (hash & unchecked((Int32)0xf0000000));
    

    (当然所有其他 UInt32 事件都应更改为 Int32)。 应该可以的。

    【讨论】:

    • 谢谢。我认为这正是我所需要的。
    猜你喜欢
    • 2018-02-23
    • 1970-01-01
    • 2011-04-23
    • 2017-09-19
    • 1970-01-01
    • 2019-10-27
    • 2019-05-23
    • 2016-06-23
    • 2020-12-09
    相关资源
    最近更新 更多