在C#中对char数组的异地进行异或后,无法获得与Delphi代码相同的结果

问题描述 投票:0回答:1

参数:InLong = 0,Posit = 5,来自ASCII文件TmPChar {。,STX,NUL,NUL}

德尔福代码

Procedure TForm1.GetLongFromBuf(Var InLong : Longint; Posit : Integer; ZRepB : ZrepBuf);
Var
  TmpPChar     : Array[0..3] Of Char;
  PLong        : ^Longint;
  I            : Byte;
Begin
For I:= 0 To 3 Do
   TmpPChar[I] := ZRepB[Posit+I];
PLong := @TmpPChar;
InLong := PLong^;
End;

输出:TmPChar {'。',#2,#0,#0},PLong = 13F54C,InLong = 558

C#代码

unsafe static long GetLongFromBuf(long InLong, int Posit, char[] ZRepB){
 long* Plong;
 char[] TmpPChar = new char[4];
 for (byte i = 0; i < TmpPChar.Length; i++){
    TmpPChar[i] = ZRepB[(Posit-1) + (i)];
 }
 fixed(char* ch = TmpPChar){
  PLong = (long*)&ch;
  InLong ^= (long)PLong;
 }
 return InLong;
}

输出:TmPChar {'。','\ u0002','\ 0','0'},PLong = 0x0000000000b3cc18,InLong = 11783192

c# delphi pointers xor unsafe
1个回答
2
投票

看来你正在使用这个Delphi代码而没有真正理解它在做什么。从您的结果中,我们可以得出结论,您使用的是Delphi的pre-unodeode版本(即:D2007或更早版本)。我们还可以猜测ZrepBuf正在定义一个字节数组或[Ansi] Char。该方法的工作原理如下:

For I:= 0 To 3 Do
  TmpPChar[I] := ZRepB[Posit+I];  /* Copy four sequential bytes to TmpPChar array */
PLong := @TmpPChar;               /* Take a pointer to the head of the array */ 
InLong := PLong^;                 /* Dereference the pointer, interpreting as a 32-bit int */

这是将四个字节转换为32位整数的代码。在Delphi中,LongInt类型是32位integer类型的别名,相当于C#中的int类型,而不是long。 Delphi代码中没有使用XOR运算符。在PLong^中,^算子是一个解除引用操作。

在C#中,您可以完全避免使用unsafe代码,只需使用BitConverter类执行此转换:

 byte[] b = new byte[4] { 0x2E, 0x02, 0x00, 0x00 }; 
 int result = BitConverter.ToInt32(b, 0);  // result == 558

在这里,我将输入数组定义为byte[],因为C#中的char(以及Delphi 2009或更新版本中)是用​​于存储Unicode字符的16位类型(两个字节)。您正在读取的数据是ANSI编码的 - 我假设您了解如何将文本文件读入字节数组。

顺便提一下,在更现代的Delphi中,您还可以重写上面的指针代码,使用TEncoding类以类似于C#中的as described here类的方式执行此函数BitConverter

© www.soinside.com 2019 - 2024. All rights reserved.