user1030312
user1030312

Reputation:

Efficient way to untranspose the bit of an integer array?

Consider 3 integers of 2 bits, stored in an array

x1 = [ 
    ad,
    be,
    cf,
]

The integers are shown above with their bits, but they are stored as regular int.
The array x1 is the transpose of the integer x = abcdef.

How to untranspose x1 to get

x2 = [ 
    ab,
    cd,
    ef,
]

The array x2 is simply x in natural order.

What is an efficient way to do this in python?

My ultimate goal is to do comparison between integers.
So given integers a and b stored like x1, I want to know if a > b, by looking at a1 and b1.
Any way to achieve this goal, is a good answer as well.

I can use a string representation of integers, but I would like to use some bit shift magic.

This question is a converse to Efficient way to transpose the bit of an integer in python?

Upvotes: 1

Views: 112

Answers (1)

John Coleman
John Coleman

Reputation: 51998

Here is one way:

def untranspose(arr):
    x,y,z = arr
    a,d = divmod(x,2)
    b,e = divmod(y,2)
    c,f = divmod(z,2)
    return f + 2*e + 4*d + 8*c + 16*b + 32*a

For example,

>>> untranspose([1,3,2])
30

[1,3,2] corresponds to

01
11
10

so you want the integer 011110:

>>> int('011110',2)
30

Upvotes: 2

Related Questions