我需要通过网络从C#向Python发送一个整数,如果两种语言中的“规则”相同,那么它们的字节大小应该与缓冲区大小相同,我可以只是Python中的int(val)
...我不能?
两者的大小都是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 :(得分:3)
data = int( conn.recv(32) );
int(string)
执行int('42') == 42
和int('-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#,所以我不能告诉你如何正确地做到这一点。任何人都可以随时修改。