2012-07-04 18 views
1

我想這個代碼特定部分的C++轉換到Python 但在做的像蟒蛇的memset和sprintf操作我被困。 任何人都可以幫助我做同樣的python.My代碼如下。Python中的sprintf和memset操作

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 
} 

這些東西我試圖

#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))) 
+0

什麼是你的問題? – georg

+0

誰能幫我做上面的C代碼在Python –

+1

答案或許是肯定的。總有人喜歡做別人的工作。 – georg

回答

4

在Python sprintf通過使用%.format實現,例如:

headerInfo = '%d' % packetLength 
# or, 
headerInfo = '{0:d}'.format(packetLength) 
# or even 
headerInfo = str(packetLength) 

memset樣操作可通過乘法來完成,例如:

headerInfo = '\0' * 32 

然而,這些不會像你期望的那樣,因爲字符串是不可變的。你需要做的是這樣的:

headerInfo = str(packetLength) 
headerInfo += '\0' * (32 - len(headerInfo)) # pad the string 
dataBuffer = headerInfo + data 

或者使用struct模塊:(該32s格式字符串將左對齊的字符串,使用NULL字符)

import struct 
dataBuffer = struct.pack('32ss', str(packetLength), data) 


如果您正在使用Python 3,那你就要小心字節VS字符串。如果你正在處理網絡套接字等,你想確保一切都是字節,而不是unicode字符串。

+0

這很好,謝謝你,夥計。 –

+1

@AkhilThayyil,沒問題,但在未來的問題上,請指出你已經付出了努力(比如,發表任何你寫過的Python代碼),而不是隻問「寫我的代碼「。 – huon

+0

真實的要求是有點不同,我試了很多東西,請在我的編輯,發現後,只有我發佈的問題... –