在Python中的一个整数位修改 [英] Modify bits in an integer in Python

查看:771
本文介绍了在Python中的一个整数位修改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,我有一个值7(0b00000111)一个整数,我想用一个函数到13(0b00001101)那么,什么是更换一个整数字节的最佳算法来代替它?例如:

  SET_BITS(someValue中,3,1)#是什么让第3位〜1 someValue中?


解决方案

您只需要:

 高清SET_BIT(V,指数,X):
  设置索引:第v到x的位,并返回新的价值。
  屏蔽= 1<<指数
  V&安培; =〜面膜
  如果x:
    V | =面膜
  返回v>>> SET_BIT(7,3,1)
15
>>> SET_BIT(SET_BIT(7,1,0),3,1)
13

请注意该位数字(首页)是从0,0是最显著位。

So, I have an integer with a value 7. (0b00000111) And I would like to replace it with a function to 13. (0b00001101) So what is the best algorithm to replace bytes in an integer? For example:

set_bits(somevalue, 3, 1) # What makes the 3rd bit to 1 in somevalue?

解决方案

You just need:

def set_bit(v, index, x):
  """Set the index:th bit of v to x, and return the new value."""
  mask = 1 << index
  v &= ~mask
  if x:
    v |= mask
  return v

>>> set_bit(7, 3, 1)
15
>>> set_bit(set_bit(7, 1, 0), 3, 1)
13

Note that bit numbers (index) are from 0, with 0 being the least significant bit.

这篇关于在Python中的一个整数位修改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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