试图将c#脚本重写为Python,但不工作

本文关键字:Python 工作 重写 脚本 | 更新日期: 2023-09-27 18:17:25

我正在尝试将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

这是我在Python中调用encodeLength(55) + encodeLength(len("Testing.")) + "Testing."的响应。

641196472Testing.

有谁知道为什么不返回c#生成的输出?

试图将c#脚本重写为Python,但不工作

在Python中,str(x)不会将char代码(ASCII值)转换为相应的char。使用chr(x)来实现这一点。str(x)将对象转换为字符串,这意味着ASCII码64被转换为字符串"64",而不是chr(x)返回的"@"