所以我想要在C#中重新创建一些Python源代码。代码是关于读取和解密二进制文件。我已经在现有文件上测试了该函数,它运行时没有错误;虽然结果字符串没有乱码或任何东西,但它似乎对我没用。但这超出了这个问题的范围,我只想知道我是否已将函数正确地转换为C#,因此它与Python中的相同。
Python代码:
filename = os.path.basename(path_and_filename)
key = 0
for char in filename:
key = key + ord(char)
f = open(path_and_filename, 'rb')
results = ''
tick = 1
while True:
byte = f.read(2)
if byte:
if tick:
key = key + 2
else:
key = key - 2
tick = not tick
res = struct.unpack('h', byte)[0] ^ key
results = results + chr(res)
continue
break
f.close()
return results
path_and_filename是加密文件的绝对路径。这是我写的C#代码:
string path = @"C:\Program Files (x86)\Steam\steamapps\common\SolForge\data\released\c28556fb686c8d07066419601a2bdd83\Game_Keywords.dat";
char[] chars = "c28556fb686c8d07066419601a2bdd83".ToCharArray();
int key = 0;
foreach (char c in chars)
{
key += c;
}
StringBuilder builder = new StringBuilder();
using (FileStream file = new FileStream(path, FileMode.Open))
{
bool tick = true;
while (true)
{
int i = file.ReadByte();
if (i == -1)
break;
if (tick)
key += 2;
else
key -= 2;
tick = !tick;
//The next 2 lines are for parsing the short, equivalent(?) to struct.unpack('h', byte)
i <<= 8;
i += file.ReadByte();
i ^= key;
byte b = (byte)i;
char c = (char)b;
builder.Append(c);
}
}
string result = builder.ToString();
别介意代码的肮脏。这两个片段是否会将相同的输出提供给某个输入?