C#代码移植到Python的结果不一样
所以我最近进入了Python,我有一个项目,我正试图从C#移植到Python 为了进一步了解python的工作原理,我遇到了这个麻烦 我无法获得与C代码相同的输出 C#代码:将长度输出为C#代码移植到Python的结果不一样,python,c#,Python,C#,所以我最近进入了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); Co
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);
}
我做错了什么
感谢您的时间和努力。对于C部分,这是因为您声明的数组长度为46。(json.Length
最初是43,在send_request
中添加+2后,数组的大小将是45。)
注意数组=新字节[message.Length+1]
。此时,message.Length
为45。因此,添加+1将得到46,如Console.WriteLine(array.Length)中所示代码>
对于python,只是一个猜测:是否pythonsprint(len(array))
只打印实际填充值的长度
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()