python中二进制数据的长度

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/40726217/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 23:54:31  来源:igfitidea点击:

Length of binary data in python

pythonbytepython-2.x

提问by Matthew

I am using Python. I am trying to determine the correct length of bytes in a binary set of data.

我正在使用 Python。我正在尝试确定二进制数据集中的正确字节长度。

If I assign a variable the binary data...

如果我分配一个变量二进制数据......

x = "aabb".decode("hex")

is that the same as

是不是一样

x = b'aabb'

And if so, how do you get how many bytes that is? (It should be 2 bytes)

如果是这样,您如何获得多少字节?(应该是2个字节)

When I try:

当我尝试:

len(x)

I get 4 instead of 2 though...

不过我得到 4 而不是 2...

I am worried that x is turned into a string or something else I don't understand because the data types are so fluid in Python...

我担心 x 变成字符串或其他我不明白的东西,因为 Python 中的数据类型是如此流畅......

回答by wim

The length of binary data is just the len, and the type is strin Python-2.x (or bytesin Python-3.x). However, your object 'aabb'does not contain the two bytes 0xaa and 0xbb, rather it contains 4 bytes corresponding with ASCII 'a' and 'b' characters:

二进制数据的长度为len,类型str在 Python-2.x(或bytesPython-3.x)中。但是,您的对象'aabb'不包含两个字节 0xaa 和 0xbb,而是包含与 ASCII 'a' 和 'b' 字符对应的 4 个字节:

>>> bytearray([0x61, 0x61, 0x62, 0x62])
bytearray(b'aabb')
>>> bytearray([0x61, 0x61, 0x62, 0x62]) == 'aabb'
True

This is probably the equivalence you were actuallylooking for:

这可能是您实际寻找的等效项:

>>> 'aabb'.decode('hex') == b'\xaa\xbb' 
True

The following items are all equal (and length 2):

以下项目都是相等的(和 length 2):

>>> s1 = 'aabb'.decode('hex')
>>> s2 = b'\xaa\xbb'
>>> s3 = bytearray([0xaa, 0xbb])
>>> s4 = bytearray([170, 187])
>>> s1 == s2 == s3 == s4
True