Python:如何从字节中提取特定位? [英] Python: How do I extract specific bits from a byte?

查看:72
本文介绍了Python:如何从字节中提取特定位?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一条消息,内容为 14 09 00 79 3d 00 23 27.我可以通过调用 message[4] 从这个消息中提取每个字节,例如,它会给我 3d.我如何从这个字节中提取单独的 8 位?例如,我如何将第 24-27 位作为单个消息?仅位 28 怎么样?

I have a message which reads as 14 09 00 79 3d 00 23 27. I can extract each byte from this message by calling message[4], which will give me 3d for example. How do I extract the individual 8 bits from this byte? For example, how would I get bits 24-27 as as single message? How about just bit 28?

推荐答案

要回答问题的第二部分,您可以使用按位运算获得特定的位值

To answer the second part of your question, you can get specific bit values using bitwise operations

# getting your message as int
i = int("140900793d002327", 16)
# getting bit at position 28 (counting from 0 from right)
i >> 28 & 1
# getting bits at position 24-27
bin(i >> 24 & 0b111)

这篇关于Python:如何从字节中提取特定位?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆