I want to convert this particular portion of code in C++ to python
But i got stuck while doing the operations like memset and sprintf in python.
Can anyone help me to do the same in python.My code is as follows.
send(char* data)
{
/** COnvert From here **/
packetLength=strlen(data);
dataBuffer = new char[packetLength];
memset(dataBuffer, 0x00, packetLength);
char headerInfo[32];
memset(headerInfo, 0x00, sizeof (headerInfo));
sprintf(headerInfo, "%d", packetLength);
memcpy(dataBuffer, headerInfo, 32);
memcpy(dataBuffer + 32, data, packetLength);
/** Upto Here **/
//TODO send data via socket
}
These things i have tried
#headerInfo=bytearray()
#headerInfo.insert(0,transactionId)
#headerInfo.insert(self.headerParameterLength,(self.headerLength+len(xmlPacket)))
#headerInfo=(('%16d'%transactionId).zfill(16))+(('%d'%(self.headerLength+len(xmlPacket))).zfill(16))
#print("Sending packet for transaction "+(('%d'%transactionId).zfill(16))+" packetLength "+(('%d'%(self.headerLength+len(xmlPacket))).zfill(16)))
#dataPacket=headerInfo+xmlPacket
headerInfo=('%0x0016d'%transactionId)+('%0x00d'%(self.headerLength+len(xmlPacket)))
sprintfin Python is achieved by using%or.format, e.g.:A
memset-like operation can be done via multiplication, e.g.:However, these won’t act like you expect, since strings are immutable. You need to do something like:
Or use the
structmodule:(The
32sformat string will left-align the string and pad with NUL characters.)If you are using Python 3, then you have to be careful about bytes vs strings. If you are dealing with network sockets etc. you want to make sure that everything is bytes, not unicode strings.