如何修改整数位? [英] How to modify bits in an integer?

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

问题描述

我有一个值为7(0b00000111)的整数,我想将其替换为13(0b00001101)的函数.替换整数位的最佳算法是什么?

I have an integer with a value 7 (0b00000111) And I would like to replace it with a function to 13 (0b00001101). What is the best algorithm to replace bits in an integer?

例如:

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

推荐答案

您只需要:

def set_bit(v, index, x):
  """Set the index:th bit of v to 1 if x is truthy, else to 0, and return the new value."""
  mask = 1 << index   # Compute mask, an integer with just bit 'index' set.
  v &= ~mask          # Clear the bit indicated by the mask (if x is False)
  if x:
    v |= mask         # If x was True, set the bit indicated by the mask.
  return v            # Return the result, we're done.

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

请注意,位数(index)从0开始,其中0是最低有效位.

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

还要注意,新值是 returned ,没有办法像显示的那样修改整数就地"(至少我不这么认为).

Also note that the new value is returned, there's no way to modify an integer "in place" like you show (at least I don't think so).

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

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