Efficient Way To Transpose The Bit Of An Integer In Python?
Consider a 6 bits integer x = a b c d e f 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 pyth
Solution 1:
This should work:
mask = 0b100100
for i in range(2, -1, -1):
tmp = x & mask
print(((tmp >> 3 + i) << 1) + ((tmp & (1 << i)) >> i))
mask >>= 1
The first mask extracts only a
and d
, then it is shifted to extract only b
and e
and then c
and f
.
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.
Solution 2:
Slices will work if your working with strings ( bin(x)
).
>>>>>>HInt = 'ABCDEFGHIJKLMNO'>>>x = []>>>for i in [0, 1, 2]:
x.append(HInt[i::3])
>>>x[0]
'ADGJM'
>>>x[1]
'BEHKN'
>>>x[2]
'CFILO'
>>>
Post a Comment for "Efficient Way To Transpose The Bit Of An Integer In Python?"