[英]Writing equivalent code in Pascal to code C#
我试图将此代码在pascal中转换为c#。 没有编译错误,该方法适用于短字符串(4个或5个字符)。 所有方法和函数都是等效的,但是我的代码抛出此异常:
System.OverflowException:一个字符的值太大或太小。
这是StackTrace
:
在ConsoleApplication3.Program.Encrypt(布尔加密,字符串字,Int32 startKey,Int32 multKey,Int32 addKey)的System.Convert.ToChar(Int32值)中位于c:\\ Users \\ TRS \\ Documents \\ Visual Studio 2013 \\ Projects \\ ConsoleApplication3 \\ ConsoleApplication3 \\ Program.cs:第29行。
这是Pascal代码:
function TGenericsF.Encrypter(Encrypt: WordBool; Source: AnsiString;
StartKey, MultKey, AddKey: Integer): AnsiString;
{$R-} {$Q-}
var Counter: LongInt;
S: AnsiString;
Ret: AnsiString;
begin
S := Source;
Ret := '';
for Counter := 1 to Length(S) do
begin
if Encrypt then
begin
Ret := Ret + AnsiChar(Ord(S[Counter]) xor (StartKey shr 8));
StartKey := (Ord(Ret[Counter]) + StartKey) * MultKey + AddKey;
end
else
begin
Ret := Ret + AnsiChar(Ord(S[Counter]) xor (StartKey shr 8));
StartKey := (Ord(S[Counter]) + StartKey) * MultKey + AddKey;
end;
end;
Result := Ret;
end;
这是我等效的C#代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication3
{
class Program
{
static void Main(string[] args)
{
string username = Encrypt(true, "Administrator", 8, 12, 16);
Console.WriteLine(username);
Console.ReadKey();
}
public static string Encrypt(bool encrypt, string word, int startKey, int multKey, int addKey)
{
string encryptedWord = string.Empty;
for (int i = 0; i < word.Length; i++)
{
if(encrypt)
{
encryptedWord += Convert.ToChar(word[i] ^ (startKey >> 8));
startKey = (((int)encryptedWord[i]) + startKey) * multKey + addKey;
}
else
{
encryptedWord += Convert.ToChar(word[i] ^ (startKey >> 8));
startKey = (((int)word[i]) + startKey) * multKey + addKey;
}
}
return encryptedWord;
}
}
}
非常感谢。
解决此问题的第一步是认识到加密对字节数组进行操作,然后返回字节数组。 这里没有放置字符串的地方。 文本编码只是掩盖了加密算法。 如果需要加密字符串,则必须首先使用一些定义良好的文本编码将其转换为字节数组。
因此,让我们使用该策略重新编写Delphi代码。 看起来像这样:
{$R-} {$Q-}
function EncryptDecrypt(Encrypt: Boolean; const Source: TBytes;
StartKey, MultKey, AddKey: Integer): TBytes;
var
i: Integer;
begin
SetLength(Result, Length(Source));
for i := low(Source) to high(Source) do
begin
if Encrypt then
begin
Result[i] := Source[i] xor (StartKey shr 8);
StartKey := (Result[i] + StartKey) * MultKey + AddKey;
end
else
begin
Result[i] := Source[i] xor (StartKey shr 8);
StartKey := (Source[i] + StartKey) * MultKey + AddKey;
end;
end;
end;
在C#中复制此代码很容易。 我们只需要确保我们允许溢出的方式与Delphi代码相同即可。 这涉及使用unchecked
。 代码运行如下:
public static byte[] EncryptDecrypt(bool Encrypt, byte[] Source,
int StartKey, int MultKey, int AddKey)
{
byte[] Dest = new byte[Source.Length];
for (int i = 0; i < Source.Length; i++)
{
if (Encrypt)
{
unchecked
{
Dest[i] = (byte) (Source[i] ^ (StartKey >> 8));
StartKey = (Dest[i] + StartKey) * MultKey + AddKey;
}
}
else
{
unchecked
{
Dest[i] = (byte) (Source[i] ^ (StartKey >> 8));
StartKey = (Source[i] + StartKey) * MultKey + AddKey;
}
}
}
return Dest;
}
我的一些粗略测试表明:
您的代码导致错误,因为已检查算法是否溢出。 您的算术溢出了int
数据类型,并且由于它在检查的上下文中执行,因此该溢出导致错误。 该文档有详细信息: http : //msdn.microsoft.com/zh-cn/library/khy08726.aspx
unchecked
关键字可抑制该错误并允许溢出发生。 Delphi代码使用{$Q-}
来达到相同的效果。
Pascal的AnsiChar是一个八位值。 可能允许任何下溢或上溢。
您可能想编写C#代码以使用字节数组而不是字符和字符串,因为C#字符为16位。
如果代码取决于上溢/下溢的工作原理,则使用字节将对其进行修复。
正如David Crowell正确指出的那样,AnsiChar是1个字节的值。 因此,您需要更改以下内容:
encryptedWord += Convert.ToChar(word[i] ^ (startKey >> 8));
变成这样的东西:
encryptedWord += (char)((byte)(word[i] ^ (startKey >> 8)) & 0xFF);
另外,您在C#中的代码效率很低。 我会这样做:
public static string Encrypt(bool encrypt, string word, int startKey, int multKey, int addKey)
{
try
{
StringBuilder encryptedWord = new StringBuilder(word.Length);
for (int i = 0; i < word.Length; i++)
{
encryptedWord.Append((char)((byte)(word[i] ^ (startKey >> 8)) & 0xFF));
if(encrypt)
startKey = (((int)encryptedWord[i]) + startKey) * multKey + addKey;
else
startKey = (((int)word[i]) + startKey) * multKey + addKey;
}
return encryptedWord.ToString();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
throw;
}
}
更新 David Heffernan在他的两个评论中都是对的:
叹。 另一个加密问题针对字符串而不是字节数组进行操作。
和
此代码的根本问题是,它试图将字节数组填充到UTF-16编码的字符串中。 我很欣赏问题中的代码也是如此,但这确实是问题的症结所在。
如果word
包含一些值大于255的字符,则C#代码产生的结果将不同于Pascal代码产生的结果。 要解决此问题,您需要处理字节数组。 这样的事情应该做得很好:
private static byte[] StringToBytes(string str)
{
byte[] bytes = new byte[str.Length * sizeof(char)];
System.Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length);
return bytes;
}
private static string BytesToString(byte[] bytes)
{
char[] chars = new char[bytes.Length / sizeof(char)];
System.Buffer.BlockCopy(bytes, 0, chars, 0, bytes.Length);
return new string(chars);
}
public static string Encrypt(bool encrypt, string word, int startKey, int multKey, int addKey)
{
try
{
byte[] source = StringToBytes(word);
byte[] result = new byte[source.Length];
for (int i = 0; i < source.Length; ++i)
{
result[i] = (byte)((word[i] ^ (startKey >> 8)) & 0xFF);
if (encrypt)
startKey = ((result[i]) + startKey) * multKey + addKey;
else
startKey = ((word[i]) + startKey) * multKey + addKey;
}
return BytesToString(result);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
throw;
}
}
StringToBytes和BytesToString来自此处: 如何在C#中获得字符串的一致字节表示,而无需手动指定编码?
word[i] ^ (startKey >> 8)
的计算结果为81867,该值太高而无法转换为char。
当传递的值对于char而言太大时, Convert.ToChar()
会引发异常,而在Pascal中,强制转换为AnsiChar
只会截断该值。 另请注意,C#字符为16位,而在Pascal中为8位。
您可避免异常并致电之前使你的代码工作像帕斯卡尔代码通过屏蔽掉顶位Convert.ToChar
两个是追加到线encryptedWord
,就像这样:
encryptedWord += Convert.ToChar((word[i] ^ (startKey >> 8)) & 0xff);
尝试使用
Char.Parse()
而
Convert.ToChar()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.