有效的方法来转了一个Python整数位? [英] Efficient way to transpose the bit of an integer in python?
问题描述
考虑一个6位整数
x = a b c d e f
这应如下转来的2位三个整数
that should be transpose to three integers of 2 bits as follows
x1 = a d
x2 = b e
x3 = c f
什么是蟒蛇做到这一点的有效途径?
What is an efficient way to do this in python?
我目前的情况如下
bit_list = list( bin(x)[2:] ) # to chop of '0b'
# pad beginning if necessary, to make sure bit_list contains 6 bits
nb_of_bit_to_pad_on_the_left = 6 - len(bit_list)
for i in xrange(nb_of_bit_to_pad_on_the_left):
bit_list.insert(0,'0')
# transposition
transpose = [ [], [], [] ]
for bit in xrange(0, 6, 2):
for dimension in xrange(3):
x = bit_list[bit + dimension]
transpose[dimension].append(x)
for i in xrange(n):
bit_in_string = ''.join(transpose[i])
transpose[i] = int(bit_in_string, 2)
但这种调换一个5 * 1e6个电子整数位时,5位整数一百万是缓慢的。
but this is slow when transposing a 5*1e6 bits integer, to one million of 5 bits integer.
有没有更好的方法?结果
或者一些bitshit魔术<< />>
,将更快
Is there a better method?
Or some bitshit magic <</>>
that will be speedier?
这问题通过努力使斯基林希尔伯特曲线算法的Python实现相比发生
推荐答案
这应该工作:
mask = 0b100100
for i in range(2, -1, -1):
tmp = x & mask
print(((tmp >> 3 + i) << 1) + ((tmp & (1 << i)) >> i))
mask >>= 1
只有第一个面具提取物 A
和 D
,然后将其转移到只提取乙
和电子
然后 C
和˚F
。
The first mask extracts only a
and d
, then it is shifted to extract only b
and e
and then c
and f
.
在打印
语句的数字或者是 x00y00
或 0x00y0
或 00x00y
。在(TMP&GT;&GT; 3 + I)
,可将这些数字到 X
,然后&LT;&LT; 1
成于 X0
。
在((TMP及(1 LT;&LT; I))&GT;&GT; I))
先转换这些数字到 Y00
/ Y0
或是
,然后右移,以获得简单是
。总结两部分,你得到你想要的 XY
数。
In the print
statement the numbers are either x00y00
or 0x00y0
or 00x00y
. The (tmp >> 3 + i)
transforms these numbers into x
and then the << 1
obtains x0
.
The ((tmp & (1 << i)) >> i))
first transforms those numbers into y00
/y0
or y
and then right-shifts to obtain simply y
. Summing the two parts you get the xy
number you want.
这篇关于有效的方法来转了一个Python整数位?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!