简体   繁体   English

获取二进制数据的字节大小(python3.6)

[英]Get byte size of the binary data (python3.6)

I have a string which I converted to binary representation using str.encode('utf-8') .我有一个字符串,我使用str.encode('utf-8')其转换为二进制表示。 After that I expect getsizeof() and len() return the same value, but it appears that sys.getsizeof() always return a bigger value.之后我希望getsizeof()len()返回相同的值,但似乎sys.getsizeof()总是返回一个更大的值。

I then send this binary data over socket to node.js server and store them in Buffer.然后我通过套接字将此二进制数据发送到 node.js 服务器并将它们存储在缓冲区中。 Both Buffer.length and Buffer.byteLength return the same value, which is equal to len() value in Python. Buffer.lengthBuffer.byteLength返回相同的值,它等于 Python 中的len()值。

I can't figure out what is going on there and why Buffer.byteLength is not the same as sys.getsizeof() .我无法弄清楚那里发生了什么以及为什么Buffer.byteLengthsys.getsizeof()

My data is not always strings or may have different encoding, so I want to make sure that I know the size in bytes, not in characters.我的数据并不总是字符串或可能有不同的编码,所以我想确保我知道以字节为单位的大小,而不是以字符为单位。

sys.getsizeof returns the size that the object takes in memory. sys.getsizeof返回对象在内存中占用的大小。 That includes all additional data which Python needs in order to work with the object (eg the information that this is a string in the first place and not an integer).这包括 Python 处理对象所需的所有附加数据(例如,这首先是字符串而不是整数的信息)。

For example, see that it has a certain size for an empty string:例如,看到它有一个空字符串的特定大小:

>>> sys.getsizeof('')
49

and even for None :甚至对于None

>>> sys.getsizeof(None)
16

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM