1

我需要通过网络从 C# 向 Python 发送一个整数,我发现如果两种语言的“规则”相同,并且它们的字节大小相同,应该是缓冲区大小,我可以int(val)在 Python 中......我不能吗?

两者都有 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");
4

1 回答 1

3
data = int( conn.recv(32) );
  1. 那是 32 字节而不是 32 位
  2. 这是一个最大值,你得到的可能比你要求的少
  3. 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#,所以我不能告诉你如何正确地做到这一点。任何这样做的人,请随时在更正中进行编辑。

于 2012-08-05T14:20:46.260 回答