python中二进制数据的长度

编程入门 行业动态 更新时间:2024-10-25 04:25:37
本文介绍了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中二进制数据的长度

本文发布于:2023-10-09 18:09:10,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1476413.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:长度   二进制数   python

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!