Skip to content
Advertisement

How to change binary value to an array with individual states

I have a question. How can I import value like this:

value = 0b1010

to an array like this:

array = np.array([1, 0, 1, 0])

and vice versa?

Advertisement

Answer

np.binary_repr function turn integers into binary representation string, so you could do:

import numpy as np
value = 0b1010
arr = np.array(list(np.binary_repr(value)),dtype=int)
print(arr)

Output:

[1 0 1 0]

Reverse direction (as requested by @sai):

arr = np.array([1,0,1,0],dtype=int)
value = np.sum(arr * [2**i for i in reversed(range(len(arr)))])
print(value)

Output:

10

Explanation: I build list with desceding powers of 2 (in this case [8,4,2,1]) using list comprehension then multiply arr (i.e. multiply pairwise elements from arr and said list) then np.sum.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement