python中二进制数据的长度 [英] Length of binary data in python
问题描述
我正在使用Python。我正在尝试确定二进制数据集中字节的正确长度。
I am using Python. I am trying to determine the correct length of bytes in a binary set of data.
如果我为变量分配了二进制数据...
If I assign a variable the binary data...
x = "aabb".decode("hex")
与
x = b'aabb'
如果是的话,如何获得多少字节? (应该为2个字节)
And if so, how do you get how many bytes that is? (It should be 2 bytes)
当我尝试:
len(x)
虽然我得到了4个而不是2个...
I get 4 instead of 2 though...
我担心x会变成字符串或其他我不理解的东西,因为数据类型在Python中是如此不稳定...
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...
推荐答案
二进制数据的长度仅为 len
,类型为 str
在Python-2.x中(或 bytes
在Python-3.x中)。但是,您的对象'aabb'
不包含两个字节0xaa和0xbb,而是包含4个字节,分别对应ASCII'a'和'b'字符:
The length of binary data is just the len
, and the type is str
in Python-2.x (or bytes
in 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:
>>> bytearray([0x61, 0x61, 0x62, 0x62])
bytearray(b'aabb')
>>> bytearray([0x61, 0x61, 0x62, 0x62]) == 'aabb'
True
这可能实际上是您实际上在寻找的等效项:
This is probably the equivalence you were actually looking for:
>>> 'aabb'.decode('hex') == b'\xaa\xbb'
True
以下各项均相等(且长度 2
):
The following items are all equal (and length 2
):
>>> s1 = 'aabb'.decode('hex')
>>> s2 = b'\xaa\xbb'
>>> s3 = bytearray([0xaa, 0xbb])
>>> s4 = bytearray([170, 187])
>>> s1 == s2 == s3 == s4
True
这篇关于python中二进制数据的长度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!