Question

i have a 3D array of int32. I would like to transform each item from array to its corresponding bit value on "n" th position. My current approach is to loop through the whole array, but I think it can be done much more efficiently.

for z in range(0,dim[2]):
 for y in range(0,dim[1]):
  for x in range(0,dim[0]):
   byte='{0:032b}'.format(array[z][y][x])
   array[z][y][x]=int(byte>>n) & 1

Looking forward to your answers.

Was it helpful?

Solution

If you are dealing with large arrays, you are better off using numpy. Applying bitwise operations on a numpy array is much faster than applying it on python lists.

import numpy as np
a = np.random.randint(1,65, (2,2,2))

print a
Out[12]: 
array([[[37, 46],
        [47, 34]],

       [[ 3, 15],
        [44, 57]]])
print (a>>1)&1
Out[16]: 
array([[[0, 1],
        [1, 1]],

       [[1, 1],
        [0, 0]]])

OTHER TIPS

Unless there is an intrinsic relation between the different points, you have no other choice than to loop over them to discover their current values. So the best you can do, will always be O(n^3)

What I don't get however, is why you go over the hassle of converting a number to a 32bit string, then back to int.

If you want to check if the nth bit of a number is set, you would do the following:

power_n = 1 << (n - 1)
for z in xrange(0,dim[2]):
 for y in xrange(0,dim[1]):
  for x in xrange(0,dim[0]):
   array[z][y][x]= 0 if array[z][y][x] & power_n == 0 else 1

Not that in this example, I'm assuming that N is a 1-index (first bit is at n=1).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top