2012-08-05 23 views
1

我需要通過網絡發送一個從C#到Python的整數,它打擊了我,如果兩個語言的「規則」相同,並且它們的字節大小相同,應該是緩衝區大小,我可以int(val)在Python中......我不能嗎?C#和Python中的int是一樣的嗎?

雙方都有大小爲32位,所以在Python和C#我應該能夠設置

C#:

String str = ((int)(RobotCommands.standstill | RobotCommands.turncenter)).ToString(); 
Stream stream = client.GetStream(); 

ASCIIEncoding asen = new ASCIIEncoding(); 
byte[] ba = asen.GetBytes(str); 

stream.Write(ba, 0, 32); 

的Python:

while True: 
    data = int(conn.recv(32)); 

    print "received data:", data  

    if((data & 0x8) == 0x8): 
     print("STANDSTILL"); 

    if((data & 0x20) == 0x20): 
     print("MOVEBACKWARDS"); 
+0

爲什麼不試試看看會發生什麼? – 2012-08-05 13:06:08

+1

@MichaelMauderer可能會出現一些不明確的情況,它會出錯。我問這個問題沒有問題。 – 2012-08-05 13:07:08

+0

您的C#代碼是否運行?你聲稱你的int的字符串表示有32個字節,這顯然沒有。 – CodesInChaos 2012-08-05 13:10:03

回答

3
data = int(conn.recv(32)); 
  1. 這是32個字節不是32位
  2. 這是一個最大值,你可能會得到更少的請求
  3. int(string)確實像int('42') == 42int('-56') == -56這樣的東西。這是它將一個可讀的數字轉換爲一個int。但這不是你在這裏處理的。

你想要做這樣的事

# see python's struct documentation, this defines the format of data you want 
data = struct.Struct('>i') 
# this produces an object from the socket that acts more like a file 
socket_file = conn.makefile() 
# read the data and unpack it 
# NOTE: this will fail if the connection is lost midway through the bytes 
# dealing with that is left as an exercise to the reader 
value, = data.unpack(socket_file.read(data.size)) 

編輯

看起來你也是在C#代碼錯誤地發送數據。我不知道C#,所以我不能告訴你如何正確地做到這一點。任何人都可以在修改中隨意編輯。

相關問題