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);

パイソン:

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 に答える