python求一个整数的个位_在Python中的一个整数位修改

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值