Convert A Numpy Bool Array To Int
I have a numpy array (dtype bool) representing an array of bits. For example, the array
np.array([True, False, False], dtype=bool) represents the number 4 (indeed,
bin(4) == 0b100).
I would like to convert the numpy array to an integer (
4 in the previous example).
So far I've tried with an iterative approach:
bits = np.array([True, False, False], dtype=bool) n = 0 for bit in bits: n = (n << 1) | bit
This approach does work, but I would prefer something that does not iterate over every element of the array, possibly a numpy built-in method.
bits = np.array([True, False, False], dtype=bool) n = np.packbits(np.pad(bits, ((8 - len(bits) % 8) % 8, 0))).item()
This approach only works for arrays with 8 or less elements. Indeed, if you try to use a longer array you end up having multiple results (because apparently
packbits not only pads to the right but also converts every single byte to a number):
bits = np.array( [True, False, False, False, False, False, False, False, False], dtype=bool, ) n = np.packbits(np.pad(bits, ((8 - len(bits) % 8) % 8, 0))) print(n) # this prints [1 0], but I need it to return 256
np.array([True, True], dtype=bool) --> 3 np.array([True, True, False], dtype=bool) --> 6 np.array([True, False, False, True, True], dtype=bool) --> 19 np.array([True, False, False, False, False, False, False, True, False, False], dtype=bool) --> 516
You can solve this problem by generating the power of two starting from the biggest one (eg.
[16, 8, 4, 2, 1]), and then multiply this by
bits before doing the final sum:
powers = 1 << np.arange(bits.size, dtype=np.uint64)[::-1] result = np.sum(powers * bits)
This is equivalent of doing:
2**n * bits + 2**(n-1) * bits + ... + 2**0 * bits[n].
Note that the final value needs to fit in 64 bits.
- → What are the pluses/minuses of different ways to configure GPIOs on the Beaglebone Black?
- → Django, code inside <script> tag doesn't work in a template
- → React - Django webpack config with dynamic 'output'
- → GAE Python app - Does URL matter for SEO?
- → Put a Rendered Django Template in Json along with some other items
- → session disappears when request is sent from fetch
- → Python Shopify API output formatted datetime string in django template
- → Shopify app: adding a new shipping address via webhook
- → Shopify + Python library: how to create new shipping address
- → shopify python api: how do add new assets to published theme?
- → Access 'HTTP_X_SHOPIFY_SHOP_API_CALL_LIMIT' with Python Shopify Module