python - 如何根据python中的位置获取十六进制数的位值

标签 python

嗨, friend 们,我是 Python 语言的新手。我正在尝试编写一些小代码,稍后我想将其集成到我的 python 模块中。这是我的问题

  1. 我在文件中有一个类似于 a[31:0]= 0X00010001 的数字,我想根据位置获取位值并根据其位值进行操作。 我想使用类似于通用类的东西,并且我正在寻找数字也超过 32 位的解决方案。 0x00010001.getbit(0) == 0 进行一些操作。期望如果 bit0 为 0 则执行操作。

  2. 我还在寻找是否有相应的掩码位,如何根据掩码位获取值 0x00010001 在这种情况下,bit[15] 是掩码,bit[0] 是值。

感谢帮助。

我尝试通过比特流模块进行操作,但没有成功

最佳答案

对于第一个问题:

def getbit(x,n):
  "Get the n-th bit of the number x"
  return x & (1 << n) and 1 or 0

说明:x & (1 << n)表示 x 之间按位与和2^n 。 表达式 P and 1 or 0意思是:如果P然后返回1,否则返回0。

这适用于任何大小的数字。 Python 并不限制您只能使用 32 位整数。

关于python - 如何根据python中的位置获取十六进制数的位值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35520438/

相关文章:

python - 如何索引列表直到遇到特定的数据类型?

python - 如何在 PythonAnywhere 上部署 web2py?

Python 正在过滤掉货币标记

python - 如何在pytest中monkeypatch动态类属性

python - Amazon EMR 集群 matplotlib 错误

python - 无法使用 print(var,end ='' ) 逐行输出

python - 为seaborn lmplot添加文本注释

python - pandas 数据帧的向量化操作

python - 在 Altair 中增加图表标题的字体大小

python - 在 __new__ 中执行初始化工作是 'original sin' 吗?如果是这样,如何最好地处理单例的运行一次初始化?