2012-11-15 74 views
2

我有一個TCP客戶端服務器通信。我正在發送字符串,我想測量包的大小,我該怎麼做?如何獲取字符串的大小?

在我的情況下sys.getsizeof並不好,因爲

getsizeof() calls the object’s __sizeof__ method and adds an additional garbage collector 
overhead if the object is managed by the garbage collector. 

什麼是一個字符,2個或4個字節的大小?在這種情況下,我可以簡單地測量爲msg_size = x * len(msg),但我不知道有多少字節是x

+0

len(string)返回字符串使用的字節數(len(ustring)返回字符數) – njzk2

回答

2

在Python 2.x中,str對象是8位,即每個項目1個字節。在3.x中,您可以使用bytes對象,每個對象又是1個字節。

對於處理數據,通常最好使用bytearray;這是可變的,在2.x和3.x中都是一樣的。

相關問題