简体   繁体   English

Python按位移位无法按预期工作

[英]Python Bitwise Shift doesn't work as expected

Here is my code 这是我的代码

http://pastebin.com/xRAS7qLH http://pastebin.com/xRAS7qLH

This creates an infinite loop so don't run it. 这将创建一个无限循环,因此请不要运行它。

        intMask = 0
        while(temp != 0):
            print bin(temp)[2:].zfill(32)
            temp = long(temp << 1)
            intMask += 1

When I look at the output it looks like this 当我查看输出时,它看起来像这样

11111111111111111111111100000000

111111111111111111111111000000000

1111111111111111111111110000000000

What I was expecting was something more like this 我期待的是更多这样的事情

11111111111111111111111100000000

11111111111111111111111000000000

11111111111111111111110000000000

etc 等等

There must be something different with python, or I need to typecast something? python必须有所不同,否则我需要进行类型转换? What am I missing here? 我在这里想念什么?

Python's integers have arbitrary precision, which besides being difficult to spell, means that as you bit shift, it keeps getting bigger. Python的整数具有任意精度,除了难以拼写之外,这意味着随着您的移位,它会越来越大。 If you want to limit the size, you'd want to do something like 如果要限制大小,则需要执行以下操作

temp = long(temp << 1) & (0xffffffff)

which should zero out. 应该清零。

Edit: Specifically, the & does a bitwise AND; 编辑:具体来说,&会按位执行AND; 0xffffffff (8 f's) is 32 1's (in binary) so anything within the 32 bits will be preserved; 0xffffffff(8 f)为32 1(二进制),因此将保留32位中的所有内容; anything beyond will be set to zero). 任何超出的值都将设为零)。 For more details, you could do something like: 有关更多详细信息,您可以执行以下操作:

temp = long(temp << 1) print "Before AND: ",bin(temp) temp = temp & 0xffffffff print "After AND: ", bin(temp) temp = long(temp << 1)打印“ AND之前:”,bin(temp)temp = temp&0xffffffff打印“ After AND:”,bin(temp)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM