Python中按位运算如何工作? [英] How do bitwise operations work in Python?

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

问题描述

我今天已经在学习按位运算,并且我知道Not(〜)将所有位取反,例如:

I have been learning about Bitwise operations today and I learned that Not (~) inverses all bits, e.g.:

01010
to
10101

这意味着〜10应该是-5,但我已经看到它是-11(按照python命令行)是

which means ~10 should be -5 but instead I have seen that it is -11 (per the python command line) which is

01010
to
11011

只有两个位被反转了.谁能解释为什么它不是10101?

only two of the bits have been inverted. Can anybody explain why it isn't 10101?

看完我的计算器后,我对它的理解有所提高,但是我自己的用于确定二进制和整数的代码仍然令人困惑.以字节模式输入11110101会给我-11,但在我的代码中输入的却是-117:

After looking on my calculator I understand it a little better, But my own code for determining binary and ints is still being confused. Entering in (in byte mode) 11110101 gives me -11 but the same entered in my code gives -117:

def binaryToInt(biNum, bUnsigned = False):
    iNum = 0
    bSign = int(biNum[0]) if not (bUnsigned or biNum[-1] == "u") else 0
    biNum = biNum[(1 if not (bUnsigned or biNum[-1] == "u") else 0):(len(biNum) if biNum[-1] != "u" else -1)]
    for i in xrange(len(biNum)):
        iNum += int(biNum[i]) * 2**(len(biNum) - 1 - i)
    return (iNum if not bSign else -iNum)

def intToBinary(iNum, bUnsigned = False):
    bSign = "1" if iNum < 0 else "0"
    iLoopNum = int((iNum ** 2) ** 0.5) #make positive!
    biNum = ""
    while iLoopNum:
        biNum += str(iLoopNum%2)
        iLoopNum /= 2
    return bSign + biNum[::-1] if not bUnsigned else biNum[::-1] + "u"

你们中的一个可以解释吗?

can one of you explain that?

推荐答案

11011不是 -11.您对负数的编码方案有误解.

11011 is not -11. You have a misunderstanding of the encoding scheme for negative numbers.

在二进制补码中,-11是10101,这是正确的位求反.

In two's complement, -11 is 10101 which is the correct bit inversion.

要对二进制补码求反,请将所有位取反并加一个:

To negate a two's complement number, you invert all bits and add one:

01011 eleven
10100 invert
10101 add one gives negative eleven

这篇关于Python中按位运算如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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