C# Код портирования на Python не тот же результат - PullRequest
0 голосов
/ 20 апреля 2020

поэтому я попал в Python недавно у меня есть проект, который я пытаюсь портировать с C# на Python,

Чтобы узнать больше о том, как работает python, но я столкнулся с этим проблема,

У меня проблемы с попыткой получить тот же вывод, что и код C#.

C# Код: выводит длину как 46

static void Main(string[] args)
{
    string json =
        "{\"id\":1,\"token\":\"testing\",\"type\":3,\"cmd\":1}";
    send_request(json, 3, 1);

    Console.ReadKey();
}


private static void encrypt_decrypt(byte[] data)
{
    byte[] numArray = {250, 158, 179};

    for (int index = 0; index < data.Length; ++index)
    {
        if (data[index] != numArray[index % numArray.Length])
            data[index] = (byte) (data[index] ^ (uint) numArray[index % numArray.Length]);
    }
}

public static void send_request(string str, byte type, byte cmd)
{
    byte[] bytes = Encoding.UTF8.GetBytes(str);
    byte[] array = new byte[bytes.Length + 2];

    array[0] = type;
    array[1] = cmd;

    Buffer.BlockCopy(bytes, 0, array, 2, bytes.Length);

    encrypt_decrypt(array);
    send_message(array);
}

private static void send_message(byte[] message)
{
    byte[] array = new byte[message.Length + 1];
    Buffer.BlockCopy(message, 0, array, 0, message.Length);
    array[message.Length] = 0;

    Console.WriteLine(array.Length);
}

Python Код: выводит длину как 44

def main():
    json = "{\"id\":1,\"token\":\"testing\",\"type\":3,\"cmd\":1}"
    send_request(json, 3, 1)

def encrypt_decrypt(data):
    r_list = [250, 158, 179]
    arr = bytearray(r_list)

    for i in range(len(data)):
        if data[i] is not arr[i % len(arr)]:
            data[i] = (data[i] ^ arr[i % len(arr)])


def send_request(str, type, cmd):
    print('Sending ' + str)
    str_bytes = bytes(str, 'utf-8')
    array = bytearray(len(str_bytes) + 2)
    array[0] = type
    array[1] = cmd
    array[0:2 + len(str_bytes)] = str_bytes
    encrypt_decrypt(array)
    send_message(array)


def send_message(message):
    array = bytearray(len(message) + 1)
    pos = 0
    array[pos:pos + len(message)] = message
    array[len(message)] = 0
    print(len(array))



if __name__ == '__main__':
    main()

Что я здесь не так делаю?

Спасибо, что цените ваше время и усилия.

1 Ответ

1 голос
/ 20 апреля 2020

Для части C# это потому, что вы объявляете массив длиной 46. (json.Length изначально равно 43, после добавления +2 в send_request размер array будет 45.)

Примечание array = new byte[message.Length + 1]. На данный момент message.Length равно 45. Таким образом, добавление +1 приводит к 46, как видно из Console.WriteLine(array.Length);.

Для python, только предположение: может ли быть, что питоны print(len(array)) печатают только длина фактически заполненных значений?

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...