I used tcp to send a data to python server. The data is like:
struct protocol
{
unsigned char prot;
int id;
char name[32];
}
Look at the name
field, it is a null terminated string max size is 32. Now I use strcpy
.
protocol p;
memset(&p, 0, sizeof(p));
strcpy(name, "abc");
Now I unpack it using python.
prot,id,name = struct.unpack("@Bi32s")
Now the len(name)
is 32. But I need get the string of "abc"
when the length is 3.
How can I do that?
Simply get the substring up to the first \0
:
prot,id,name = struct.unpack("@Bi32s")
name= name[:name.index("\0")]
This has the particularity that it will check and fail (throw ValueError
) if no \0
appears inside the string.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With