gpt4 book ai didi

python - Python 中以 null 结尾的字符串转换为 Int

转载 作者:行者123 更新时间:2023-11-30 15:28:22 37 4
gpt4 key购买 nike

我正在为服务器客户端架构制作一个简单的Python客户端。当我在 C 中将整数转换为字符串并通过 UDP 将其发送到 python 客户端并尝试将其转换为整数时,会出现问题,会引发异常。我认为这可能是因为 C 中的空终止字符串,所以我什至尝试消除空终止符,但没有喜悦。任何帮助将不胜感激。

Python(客户端)代码片段,我从服务器接收信息。

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

最佳答案

您可能只需要先去掉 null 即可。

例如:

portnumber = int(portnumber.strip('\x00'))

这是我通常删除空终止符的方式。尽管没有看到端口号的打印,但很难知道这是否是正确的方法。

关于python - Python 中以 null 结尾的字符串转换为 Int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26635315/

37 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com