Python中以null结尾的字符串到Int的转换
我正在为服务器-客户机体系结构制作一个简单的python客户机。当我在C中将一个整数转换成字符串,并通过UDP将其发送到python客户端并尝试将其转换成整数时,会出现异常。我认为这可能是因为C中以null结尾的字符串,所以我甚至尝试消除null终止符,但没有乐趣。任何帮助都将不胜感激 从服务器接收信息的Python(客户端)代码段Python中以null结尾的字符串到Int的转换,python,c,exception,client,server,Python,C,Exception,Client,Server,我正在为服务器-客户机体系结构制作一个简单的python客户机。当我在C中将一个整数转换成字符串,并通过UDP将其发送到python客户端并尝试将其转换成整数时,会出现异常。我认为这可能是因为C中以null结尾的字符串,所以我甚至尝试消除null终止符,但没有乐趣。任何帮助都将不胜感激 从服务器接收信息的Python(客户端)代码段 while True: try: p_ort = client_socket.recvfrom(1024) portnumb
while True:
try:
p_ort = client_socket.recvfrom(1024)
portnumber = p_ort[0]
portnumber.strip()
#portnumber = portnumber[:-1]
#portnumber.rstrip("\0")
#this is where i try to convert the string into integer but the exception is thrown
try:
port_number = int(portnumber)
except:
print "Exception"
except:
print "timeout!"
break
这是我将值发送到客户端的服务器上的代码片段
void sendDataToClient( int sfd , int index )
{
char portNum[9] = {0};
sprintf( portNum , "%d" , videos[index].port ); //videos[index].port is an integer
if( sendto( sfd , &( portNum ) , 9 , 0 , (struct sockaddr *)&client , len ) == -1 )
{
perror( "sendto()" );
}
printf("\nClient Stuff sent!\n");
}
您可能只需要首先去掉空值 例如:
portnumber = int(portnumber.strip('\x00'))
这是我通常剥离空终止符的方式。如果看不到端口号的打印,就很难知道这是否是正确的方法。提供一个简单、最少的示例将有助于人们帮助您。在本例中,只需要您接收的数据(python端)和用于解释它的代码。我对代码进行了编辑,只到了产生问题的极限。
portnumber.strip()
不会更改portnumber
,但返回了剥离的字符串。@ch3ka,为什么portnumber.rstrip(“\0”)工作?@AliAbbasJaffri,因为您没有分配它的返回值.rstrip
不会在适当的位置修改。绝对精彩!为我工作!我无法得到的是,我一直在尝试其他方法剥离空终止符,但这似乎不起作用。我尝试了“portnumber.rstrip(“\0”)”,但似乎没有任何帮助。为什么会这样?@AliAbbasJaffri,因为在C中,空字节\0实际上是十六进制值0x00,在python中是\x00。这应该很方便!非常感谢你的帮助!您还可以对空字节执行“chr(0)”。但是对于一个c程序员来说,可能不那么可读?