我正在尝试将C#脚本转换为Python。这是C#程序的样子。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
class Encoder
{
public static string encodeLength(int value, int length)
{
string stack = "";
for (int x = 1; x <= length; x++)
{
int offset = 6 * (length - x);
byte val = (byte)(64 + (value >> offset & 0x3f));
stack += (char)val;
}
return stack;
}
public static string encodeLength(string Val)
{
int value = Val.Length;
int length = 2;
string stack = "";
for (int x = 1; x <= length; x++)
{
int offset = 6 * (length - x);
byte val = (byte)(64 + (value >> offset & 0x3f));
stack += (char)val;
}
return stack;
}
public static string encodeLength(int value)
{
int length = 2;
string stack = "";
for (int x = 1; x <= length; x++)
{
int offset = 6 * (length - x);
byte val = (byte)(64 + (value >> offset & 0x3f));
stack += (char)val;
}
return stack;
}
}
这是我在C#中调用Encoder.encodeLength(55) + Encoder.encodeLength("Testing.".Length) + "Testing.
时返回的内容。
@w@HTesting.
这是我到目前为止用Python编写的内容。
def encodeLength(*args):
if len(args) == 2 and isinstance(args[0] and args[1], int):
i = 1
stack = str()
while (i <= length):
offset = 6 * (length - i)
x = 64 + (value >> offset & 0x3f)
stack += str(x)
i +=1
return stack
elif len(args) == 1 and isinstance(args[0], str):
i = 1
value = args[0]
length = 2
stack = str()
while (i <= length):
offset = 6 * (length - i)
x = 64 + (value >> offset & 0x3f)
stack += str(x)
i += 1
return stack
elif len(args) == 1 and isinstance(args[0], int):
i = 1
length = 2
stack = str()
while (i <= length):
offset = 6 * (length - i)
x = 64 + (args[0] >> offset & 0x3f)
stack += str(x)
i +=1
return stack
当我拨打encodeLength(55) + encodeLength(len("Testing.")) + "Testing."
时,这是我在Python中的回复。
641196472Testing.
有谁知道为什么这不会返回C#生成的输出?
答案 0 :(得分:4)
在Python中,str(x)
不会将char代码(ASCII值)转换为相应的char。使用chr(x)
来实现此目的。 str(x)
将对象转换为字符串,这意味着ASCII代码64
将转换为字符串"64"
,而不是"@"
,这是chr(x)
返回的内容。