我需要通过网络从 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");
最佳答案
data = int( conn.recv(32) );
- 那是 32 字节而不是 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#,所以我无法告诉您如何正确地执行此操作。任何人都可以随时在更正中进行编辑。
关于c# - C# 和 Python 中的 int 是一回事吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11816669/