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:

JavaScript

to an array like this:

JavaScript

and vice versa?

Advertisement

Answer

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

JavaScript

Output:

JavaScript

Reverse direction (as requested by @sai):

JavaScript

Output:

JavaScript

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