c# - C# 和 Python 中的 int 是一回事吗?

标签 c# python sockets tcp

我需要通过网络从 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) );
  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#,所以我无法告诉您如何正确地执行此操作。任何人都可以随时在更正中进行编辑。

关于c# - C# 和 Python 中的 int 是一回事吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11816669/

相关文章:

c# - Visual Studio 显示了很多错误,但只有一个实际错误

c# - Resharper 能否将任何代码块移动到另一个#region?

python - Python 中的嵌套默认值

python - 如何通过套接字和选择模块管理聊天服务器(Python)的套接字连接

javascript - Redux 和 Socket IO 代理错误

delphi - 如何在 delphi 中监听和重新映射 tcp 连接?

c# - 试图制作一个二维列表数组

Outlook 2013 中的 C# System.Net.Mail CSS 错误

Python 元类 : Why isn't __setattr__ called for attributes set during class definition?

python - 如何通过 tcp 接收带有线路流的 syslog-ng 日志?