如何从C解码变量字符串?

时间:2014-03-08 10:07:54

标签: python c

尝试编程UDP连接。客户端在python中,服务器在C中。

在我的python代码中,我将PDU定义为结构(使用struct模块),格式为:'B 5s 50s' (unsigned char, char[5], char[50])。问题是如果没有填充字符串,剩下的就是垃圾,我应该删除它。

从服务器解压缩响应后,如果我这样做:

str = str_from_c.split('\0',1)

它让我回答:

['useful data', '\x00\x01\x00\x00\x00r\x00\x00\x00\xae\xf2d\xb7\x18\x00\x00\x00\x02\x00\x00\x00\x0f\x00\x00\x00\x94\xecd\xb7\xa8\xe6\xb0\t\x00\x00\x00\x00\x00\xa9]\xb7\xca\xf1d\xb7']

我如何处理第二部分?

2 个答案:

答案 0 :(得分:1)

通过鄙视你的意思是 dispose ?如果你只想要文本,那么只从结果中取出 - 注意我们不会在这里调用变量str,因为这会影响内置str

text, rest = str_from_c.split('\0', 1)

然后只需使用text,如果您需要rest,您可以在以后使用它...

请注意,在拆分一次的情况下,首选str.partition,例如:

text, rest = str_from_c.partition('\0')[::2]

因为这确保始终存在3元组结果,因此即使没有发生实际拆分,解包也将始终成功。

答案 1 :(得分:0)

  

我怎么能鄙视第二部分?

只是不发送它?

服务器代码可能如下所示:

char buffer[123];
<init buffer partially, terminating the the part with a 0 >

write(..., buffer, 123);

将其更改为

write(..., buffer, strlen(buffer) + 1);