你如何扭转蟒蛇一个整数的显著位? [英] How do you reverse the significant bits of an integer in python?
问题描述
什么是扭转蟒蛇一个整数的显著位,然后把它弄出来结果整数的最佳途径?
例如我有号1,2,5,15,我想扭转位像这样:
原来逆转
1 - 0001 - 1000 - 8
2 - 0010 - 0100 - 4
5 - 0101 - 1010至1010年
15日 - 1111年至1111年 - 15
由于这些数字是32位整数我应该怎么在Python这样做吗?我不确定的部分是如何将各个位周围蟒蛇移动,如果有什么好笑这样做后,使用32位字段作为一个整数。
PS这不是功课,我只是想解决一个逻辑难题编程。
reversed_ = SUM(1 LT;<(NUMBITS-1-i)在我的范围(NUMBITS)如果原来的&GT ; I标记&放大器; 1)
What is the best way to reverse the significant bits of an integer in python and then get the resulting integer out of it?
For example I have the numbers 1,2,5,15 and I want to reverse the bits like so:
original reversed
1 - 0001 - 1000 - 8
2 - 0010 - 0100 - 4
5 - 0101 - 1010 - 10
15 - 1111 - 1111 - 15
Given that these numbers are 32 bit integers how should I do this in python? The part I am unsure about is how to move individual bits around in python and if there is anything funny about using a 32bit field as an integer after doing so.
PS This isn't homework, I am just trying to program the solution to a logic puzzle.
reversed_ = sum(1<<(numbits-1-i) for i in range(numbits) if original>>i&1)
这篇关于你如何扭转蟒蛇一个整数的显著位?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!