Python  14.slip  and slide

a = 0b101

tenth bit mask

mask = (0b1 << 9)

one less than ten

desired = a ^ mask
let's say that l want to turn on the 10th bit from the right of the integet a
instead of writing out the entire number,we slide a bit over using the << operstor.
we use 9 because we only need to slide the mask nine places over from the first
bit to reach the tenth bit .

1.define a function called flip_bit that takes the inputs(number,n).
2.filp the nth bit (with the ones bit being the first bit) and score it inresult.
3.return the result of calling bin(result).

def flip_bit(number,n)
result = (0b1 << n-1) ^ number
return bin(result)

left bit shift(<<)

0b000001 << 2 ==0b000100(1<<2 == 4)
122=4
0b000101 << 3 == 0b101000(5 << 3 ==40)
522*2 =40

right bit shift(>>)
0b0010100 >> 3==0b000010(20>>3=2)
20%3%2余2
0b0000010 >>2 == 0b0000000(2>>2 ==0)
2%2%2余0

mathematically equivalent to floor dividing and multiplying by 2(respectively) for every time you shift
but it's often easier just to think of it as shifting all the 1s and 0s left or right by the specified number of slots.

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容