Farm3256
Farm3256

Reputation: 23

Delphi function to C#

I’m trying to convert this Delphi code to C#

function TWebModule1.DecodeA(Auth: string): Word;
var
  iAuth: Cardinal;
  r: Cardinal;
begin
  iAuth := StrToInt64(Auth);
  r := (iAuth and $FFFF0000) shr 16;
  Result := (iAuth and $FFFF) xor r xor $9752;
end;

Here is what I have written in C# but it’s not giving me the expected results.

private Int64 DecodeA(Int64 auth)
{
    try
    {
        var r = (auth & 0xFFFF0000) >> 16;
        var result = (auth & 0xFFFF) ^ r ^ 0x9752;
        _log.DebugFormat("Decoding of {0} returned {1}", auth, result);
        return result;
    }
    catch (Exception ex)
    {
        _log.Fatal(ex);
        throw new Exception(ex.Message);
    }
}

Example:auth = 3216841950 should have a result of 41022

Thank you for any information you provide.

Upvotes: 2

Views: 702

Answers (2)

David Heffernan
David Heffernan

Reputation: 613451

The key understanding this it to know why the Delphi developer chose to use StrToInt64 considering that the rest of the code operates on 32 bit integers. The reason for this is that StrToInt returns a signed 32 bit integer, and so for values in the range 2^31 to 2^32 - 1 results in an error. The developer of the original Delphi code handled this by treating the input as a 64 bit integer, a data type that includes the complete range of a 32 bit unsigned type.

Now, in your C# code you can translate it very literally, but you don't need to use 64 bit types, just as the Delphi code does not. The Delphi code operates on 32 bit unsigned integers, and returns a 16 bit unsigned integer.

ushort DecodeA(uint iauth)
{
    uint r = (iauth & 0xffff0000) >> 16;
    return (ushort) (iauth & 0xffff) ^ r ^ 0x9752;
}

ushort DecodeA(string auth)
{
    return DecodeA(uint.Parse(auth));
}

Here I have provided two overloads, one for string input which parses the string, and one receives an unsigned 32 bit integer as input. The former calls the latter.

Note that I have followed the lead of the Delphi code and returned a 16 bit unsigned integer, ushort.

Upvotes: 1

Jens Borrisholt
Jens Borrisholt

Reputation: 6402

If you use the same datatypes in both languages then it works just out of the box:

Delphi version

function DecodeA(iAuth: Int64): Int64;
var
  r: Int64;
begin
  r := (iAuth and $FFFF0000) shr 16;
  Result := (iAuth and $FFFF) xor r xor $9752;
end;

C# version

private Int64 DecodeA(Int64 iAuth)
{
    Int64 r = (iAuth & 0xFFFF0000) >> 16;
    return (iAuth & 0xFFFF) ^ r ^ 0x9752;       
}

In both languages DecodeA(3216841950) equals 13361

Upvotes: 2

Related Questions