Reputation: 175
so I got into Python recently I have a project I'm trying to port from C# to Python,
To learn more on how python works but I ran into this trouble,
I'm having trouble trying to get the same output as the C# code.
C# Code: outputs the length as 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 Code: outputs the length as 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()
What am I doing wrong here?
Thank you appreciate your time and effort.
Upvotes: 0
Views: 186
Reputation: 1040
For the C#-part, that's because you're declaring the array with the length of 46. (json.Length
is initially 43, after adding +2 in send_request
, the size of array
will be 45.)
Note array = new byte[message.Length + 1]
. At this point, message.Length
is 45. Thus, adding +1 results in 46 as seen in Console.WriteLine(array.Length);
.
For python, just a guess: could it be that pythons print(len(array))
only prints the length of the actual filled values?
Upvotes: 1