如何理解我-i在python中? python中的位操作 [英] how to understand i & -i in python? bit manipulation in python

查看:161
本文介绍了如何理解我-i在python中? python中的位操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我找到&" python中的意思是基于位表达式的和"运算.最近,我发现了一个非常聪明的代码,其中一行类似于'i& -i',其中i是整数.如何理解'i& -一世'.另外,python如何处理负整数'-i'进行位操作?

I find '&' in python means 'and' operation based on bit expression. Recently, I find a very smart code and one line is like 'i & -i' where i is a integer. How to understand the result of 'i & -i'. In addition, how python deal with negative integer '-i' for bit manipulation?

推荐答案

"i& -i"-清除所有位"1",但最后一位有效. 例如:

"i & -i" - this is clear all bits "1", but last significant one. For example:

i = 10(十进制)= 000010 1 0(bin)

i = 10(dec) = 00001010(bin)

i& -i将为000000 1 0(bin)= 2(dec)

i & -i will be 00000010(bin) = 2(dec)

根据数学术语,"i&-i"返回的最大值为2 ^ N,即"i"的分母.

By math terms, "i & -i" returns maximal 2^N, which is divider of "i".

更多示例:

i(dec)   i(bin)     i&-i
 1            1        1
 5          101        1
 8         1000     1000
12         1100     0100

这篇关于如何理解我-i在python中? python中的位操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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