2012-08-05 20 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#,所以我不能告诉你如何正确地做到这一点。任何人都可以在修改中随意编辑。

相关问题